Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify an array in function?

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?

like image 965
nimcap Avatar asked Nov 09 '10 19:11

nimcap


People also ask

How do you modify an array?

You click the formula in the cell or formula bar and you can't change a thing. Array formulas are a special case, so do one of the following: If you've entered a single-cell array formula, select the cell, press F2, make your changes, and then press Ctrl+Shift+Enter..

Can an array be modified?

Arrays can be manipulated by using several actions known as methods. Some of these methods allow us to add, remove, modify and do lots more to arrays.

How do you change an array to a function in C++?

Passing Arrays To Function Instead, we pass the pointer to the array i.e. the name of the array which points to the first element of the array. Then the formal parameter that accepts this pointer is actually an array variable. As we pass the pointer, we can directly modify the array inside the function.

How do you access an array inside a function?

Pass Individual Array Elements To pass individual elements of an array to a function, the array name along with its subscripts inside square brackets [] must be passed to function call, which can be received in simple variables used in the function definition.


1 Answers

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.

like image 153
Jonas Avatar answered Sep 19 '22 04:09

Jonas