[英]change the variables of a function with two outputs in a loop in matlab
I have a function which gives me two outputs, i need to use it in a for loop to create different variables, and i want to use them later in next loops.我有一个函数,它给了我两个输出,我需要在 for 循环中使用它来创建不同的变量,我想稍后在下一个循环中使用它们。 so i need to change their name during the for loop when they are created.所以我需要在创建它们时在 for 循环期间更改它们的名称。 something like this:像这样:
for l=1:L
[A(l),B(l)] = function(l);
end
how can i do this so i could have A1,A2,... or B1,B2,.... thanks我该怎么做才能有 A1、A2、... 或 B1、B2、.... 谢谢
If you do not wish to use cell arrays you can use structure with dynamic field names:如果您不想使用元胞数组,您可以使用具有动态字段名称的结构:
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
Here is an example that you can modify to your needs.这是一个示例,您可以根据需要进行修改。
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.