Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing matrices from function to function in MATLAB

Tags:

matlab

I'm pretty new to MATLAB and I have a simple question. What if I have the following structured functions:

function[A] = test(A)
test1(A);
test2(A);
end

function test1(A)
#% do something with A
end

function test2(A)
#% do something else with the newly modified A
end

How do I pass around A from function to function keeping it's modified nature? (Suppose A is a matrix)

EDIT: let's make the situation a little simpler. Suppose my main function is:

function[a]=test(a)
test1(a);
#%test2(a);
end

and test1() is defined as:

function[a] = test1(a)
a=5;
end

Then, I call the function test with test(3), and I want it to report ans = 5, yet it still reports ans = 3.

Thanks!

like image 479
Amit Avatar asked Mar 05 '26 16:03

Amit


2 Answers

Variables in MATLAB are passed using "call by value" (with some exceptions), 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 output argument list for the function.

For your example, you would do this:

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

One thing to be aware of is variable scope. Every function has its own workspace to store its own local variables, so there are actually 3 unique A variables in the above example: one in the workspace of test, one in the workspace of test1, and one in the workspace of test2. Just because they are named the same doesn't mean they all share the same value.

For example, when you call test1 from test, the value stored in the variable A in test is copied to the variable A in test1. When test1 modifies its local copy of A, the value of A in test is unchanged. To update the value of A in test, the return value from test1 has to be copied to it.

like image 102
gnovice Avatar answered Mar 08 '26 06:03

gnovice


Return the object from the function and then pass it on to the next function.

like image 29
David Heffernan Avatar answered Mar 08 '26 06:03

David Heffernan