14

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?

1

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

nested functions, handle objects, etc. are orthogonal to copy-on-write on arrays so this does not solve the problem.
6

MATLAB is not always pass-by-value, newer versions of MATLAB do pass-by-reference under some circumstances, see in-place operations and a more general discussion about MATLAB memory management in this SO post.

Without tail-call optimization it is inefficient to use recursion and MATLAB does not have it as far I know, but every recursion can be transformed into a loop.

Comments

3

If you make your recursive function a nested function within another function where the image data is stored, then the recursive function can modify the image data without needing to have it passed to it.

2 Comments

Here's the relevant section in the documentation: mathworks.com/help/techdoc/matlab_prog/…
@Amro: Thanks, added the link to my answer.
2

This is a common misconception. Although the sytanx of MATLAB is pass by value, it does not actually pass by value as in C. The interpreter is smart enough to only make copies when necessary. So you should just go ahead and pass by value and see if you run into memory problems.

As other posters have noted, you should try to avoid recursion in MATLAB anyway.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.