I am using large arrays (about 70 MB each) and am worried about passing them to functions. My understanding is Matlab uses pass-by-value function arguments, making local copies for the called function.
As a dirty workaround, I've been declaring the large arrays as global, and manually de-allocating them when computations are completed.
My question: Is there a way to use pointers in Matlab? This is how I would do it in C/C++. If not, are there other more memory efficient methods? I've read that globals are generally a bad idea.
@mutzmatron answered my question in a comment, so this is a repost:
Actually Matlab passes by reference, unless it decides it needs to pass by value...see the explanation here: http://www.mathworks.com/matlabcentral/answers/...
I have also read everywhere that global's are generally a bad idea as well. And, specifically, I disagree. Each tool has its own purpose.
I've been working on optimizing code and have found, of all the "better options" presented, using global's in my application speeds up execution of the code by a full 20%!
The code is for processing GPS signals ... there are a number of parameters that are commonly used by all functions that define certain characteristics of a GPS signal. Also, there are numerous nested functions and iterative calls to those functions.
It might be the case that passing a single parameter to a function is somewhat faster than that function accessing a global variable. In my case, it is much faster for each function to access the 3 or 4 global variables that it needs than to pass all 10 parameters all the way up the chain of nested functions.
A tic-toc of 8.5 seconds using global variables is faster than 10.5 seconds using parameter passing or nested functions. So, bad idea? I'll take performance, thanks.
My point? Use globals if globals work better. Try it either way ... but the moment you change the large array in a function, that array now gets copied locally instead of just being referenced. I'd rather look-up a global then make a 70MB copy.
In lower-level languages, I would agree to avoid global variables the best you can ... but those languages offer pointers and constants. MATLAB just isn't made for people who actually know how to program and how to optimize. If the interpreter doesn't optimize for you; it just seems you're SOL.