在MATLAB中将矩阵从函数传递到函数 [英] Passing matrices from function to function in MATLAB
问题描述
我对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
如何在函数之间传递A并保持其修改性质? (假设A是矩阵)
How do I pass around A from function to function keeping it's modified nature? (Suppose A is a matrix)
让我们简化情况.假设我的主要功能是:
let's make the situation a little simpler. Suppose my main function is:
function[a]=test(a)
test1(a);
#%test2(a);
end
和test1()
定义为:
function[a] = test1(a)
a=5;
end
然后,我用test(3)
调用函数test
,我希望它报告ans = 5
,但它仍然报告ans = 3
.
Then, I call the function test
with test(3)
, and I want it to report ans = 5
, yet it still reports ans = 3
.
谢谢!
推荐答案
使用按值调用"(该函数的输出参数列表.
以您的示例为例,您将执行以下操作:
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
要注意的一件事是变量范围.每个函数都有其自己的工作空间来存储自己的局部变量,因此在上面的示例中实际上有3个唯一的A
变量:一个在test
的工作空间中,一个在test1
的工作空间中,一个在test1
的工作空间中. test2
的工作空间.仅仅因为它们被命名相同并不意味着它们都具有相同的价值.
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.
例如,当您从test
调用test1
时,存储在test
中变量A
中的值将被复制到test1
中变量A
中.当test1
修改其本地副本A
时,test
中A
的值不变.要更新test
中的A
的值,必须将test1
的返回值复制到该值.
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.
这篇关于在MATLAB中将矩阵从函数传递到函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!