How to modify an array in function?

nimcap picture nimcap · Nov 9, 2010 · Viewed 8.1k times · Source

MATLAB is a pass by value language. I have a recursive function that processes pixel's neighbors. It is very expensive to make the copy of the image (in my case two images) each time the function is called.

I used global variables to solve the problem. Is there any other way to make a recursive function modify an array?

Answer

Jonas picture Jonas · Nov 9, 2010

You have three options here, but maybe you don't need any of them, since Matlab used 'copy-on-write', i.e. variables are only copied if you modify them.

  1. As @gnovice mentions, you can use a nested function. Variables used inside the nested function are shared between the nested function and the enclosing function. Nested functions are somewhat tricky to debug, and a bit more complicated to write/understand.
  2. You can store your images as properties of a handle object, which is passed by reference.
  3. You can write code differently in order to not use a recursive function, since Matlab isn't the best language for using those. If you have access to the image processing toolbox, you may be able to use functions like blockproc, or im2col to rewrite the function.

Finally, if you want to stay with your current scheme, I strongly suggest using persistent variables instead of globals.