I have complex code blocks in a Matlab script that act on large, non-sparse arrays. The code performs many write operations on random elements in arrays, as well as read operations. Identical code must be executed for different (large) arrays (i.e., the same code blocks, except for different names of array variables).
I do not want to have long duplicated code blocks that differ only in array names.
Unfortunately, when I create a function to perform operations so that a block of code appears only once, performance slows down 10 or more times (presumably due to copying the array). However, I do not need the array copied. I would prefer to pass by reference, so the purpose of calling the function is ONLY to avoid duplication of code blocks. However, there seems to be no way to avoid copy-to-write semantics.
In addition, it is impossible (as I understand it) to create a script (and not a function) to achieve this, because the script must contain identical variable names as the calling script, so I would need a different script for each array on which I want to run the script. which gets nothing (I will still have duplicate blocks of code).
I considered creating an alias variable name to "replace" the array variable name of interest, in which case I could invoke a script and avoid code duplication. However, I cannot find a way to create an alias in Matlab.
Finally, I tried to write a function using the evalin() function and pass that variable the name of the array variable, but although this works, the performance is also much slower - about the same as passing arrays by value to a function (at least 10- multiple decline in performance).
I come to the conclusion that in Matlab it is impossible to avoid duplication of code blocks when performing complex operations on non-resonant arrays, trying to avoid the terrible costs that Matlab apparently offers, using any possible technique to avoid duplication of code blocks.
Itβs so hard for me to believe, but I canβt find a way around this.
Does anyone know how to avoid duplicate blocks of code when performing the same intricate operations on multiple unresolved arrays in Matlab?