在MATLAB中将矩阵从函数传递到函数 [英] Passing matrices from function to function in MATLAB

查看:473
本文介绍了在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时,testA的值不变.要更新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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆