簡體   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