简体   繁体   中英

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. so i need to change their name during the for loop when they are created. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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