3

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!

1
  • I should mention this: Each function is in its own .m file Commented Feb 6, 2011 at 16:42

2 Answers 2

6

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.

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

1 Comment

Thank you, I had figured this out earlier. This is a much more complete answer and deserves the check. Thanks again!
3

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

2 Comments

I understand this is what I need to do. But how do I do it? In C, I would just return A;. But in MATLAB?
assign the value you want to return to the name of the function, e.g. test1 = A*2;

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.