繁体   English   中英

在matlab中的循环中更改具有两个输出的函数的变量

[英]change the variables of a function with two outputs in a loop in matlab

我有一个函数,它给了我两个输出,我需要在 for 循环中使用它来创建不同的变量,我想稍后在下一个循环中使用它们。 所以我需要在创建它们时在 for 循环期间更改它们的名称。 像这样:

for l=1:L
    [A(l),B(l)] = function(l);
end

我该怎么做才能有 A1、A2、... 或 B1、B2、.... 谢谢

如果您不想使用元胞数组,您可以使用具有动态字段名称的结构

for l = 1:L
    afn = sprintf('A%d', l ); % field name for first output
    bfn = sprintf('B%d', l ); % field name for second output
    [s.(afn) a.(bfn)] = func( l );
end

fieldnames( s ); % see all created variable names

这是一个示例,您可以根据需要进行修改。

function main // because we need to call `func`

L = 5; // max num of iterations

for l = 1:L

    // replace `func` with the name of your function
    eval(['[A' num2str(l) ', B' num2str(l) '] = func(' num2str(l) ')'])

end

end

// your function goes here
function [s, c] = func(x)

s = x*x;
c = s*x;

end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM