Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables in a vector change back after the call stack returns

Tags:

vector

matlab

I am using a recursive call in a tree in matlab, the basic structure of the function is here:

function recursion(tree, targetedFeatures)

    if (some conditions fulfilled)
      return;
    end

    for i = 1:1:size(targetedFeatures,2)
      .....
      .....
       if (some conditions that using index i is true)
          targetedFeatures(1,i) = 1; 
       end
    end

    if(tree has child nodes)
       recursion(tree.child(j).targetedFeatures)
    end
end

The structure of the tree is like this:

            root
           /  |  \
          /   |   \
         /    |    \
      leaf1  leaf2  leaf3

The input parameter of function recursion is a vector named targetedFeatures, assume its initial values is [0 0 0], and in the process of visiting leaf1, the vector is changed to [1 0 0], BUT when visiting to leaf2, the targetedFeature changed back to [0 0 0].

I suspect it is because vector in matlab does not like an reference to object in other programming language?

How can I avoid this issue? Thanks.

like image 381
MengT Avatar asked Mar 25 '26 18:03

MengT


1 Answers

Matlab uses call-by-value for normal types of variables, see here. A way to work around it is to let the function return the modified copy as an output argument:

function targetedFeatures = recursion(tree, targetedFeatures)
  ...
  targetedFeatures = recursion(tree.child(j).targetedFeatures);
  ...
end

Instead, call-by-reference might be simulated by using evalin('caller', ...) and inputname.

like image 176
A. Donda Avatar answered Mar 28 '26 09:03

A. Donda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!