Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Variables in MATLAB are passed using "call by value" (<a href="http://www.mathworks.com/support/solutions/en/data/1-15SO4/?solution=1-15SO4">with some exceptions</a>), so any value that you pass to a function and modify has to be returned from the function and either placed in a new variable or the old variable overwritten. Returning the value of a variable from a function is simple: you just place the variable name in the <a href="http://www.mathworks.com/help/techdoc/matlab_prog/bresuxt-1.html#br67dei-1">output argument list</a> for the function.</p> <p>For your example, you would do this:</p> <pre><code>function A = test(A) A = test1(A); %# Overwrite A with value returned from test1 A = test2(A); %# Overwrite A with value returned from test2 end function A = test1(A) %# Pass in A and return a modified A #% Modify A end function A = test2(A) %# Pass in A and return a modified A #% Modify A end </code></pre> <p>One thing to be aware of is <a href="http://www.mathworks.com/help/techdoc/matlab_prog/f0-38052.html#f0-38068">variable scope</a>. Every function has its own workspace to store its own local variables, so there are actually 3 unique <code>A</code> variables in the above example: one in the workspace of <code>test</code>, one in the workspace of <code>test1</code>, and one in the workspace of <code>test2</code>. Just because they are named the same doesn't mean they all share the same value.</p> <p>For example, when you call <code>test1</code> from <code>test</code>, the value stored in the variable <code>A</code> in <code>test</code> is copied to the variable <code>A</code> in <code>test1</code>. When <code>test1</code> modifies its local copy of <code>A</code>, the value of <code>A</code> in <code>test</code> is unchanged. To update the value of <code>A</code> in <code>test</code>, the return value from <code>test1</code> has to be copied to it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload