简体   繁体   中英

How to create a new variable name in each iteration in a nested matlab for loop?

I would like to run my function and to create 3 different output varables.

for i=1:3
    for j=1:3
Rent_nb = landrent(i,j,Dist);
    end 
end

And I would like "_nb" to be 1, 2, 3... so I get 3 output arrays. So I looked on the internet and I saw I had to use this :
http://www.mathworks.com/matlabcentral/answers/29712-creating-a-new-variable-in-each-iteration

So that would give me :

for i=1:3
    for j=1:3
eval(['rent' num2str(i) '= landrent(i,j,Dist_lowcost)']);
    end 
end

This seems to work but I don't really understand it... I would like to get 9 outputs (one for each combination of i and j) instead of 3. I guess it has something to do with this part: num2str(i).. But I don't really understand how this works or what it does. Can someone explain/help?

Thanks

It may help to write out the command separately (to a string) and then evaluate it, and so you will be able to see exactly what statement is being evaluated:

for i=1:3
    for j=1:3
        cmd = ['rent' num2str(i) '= landrent(i,j,Dist_lowcost);'];
        fprintf('command to evaluate is: %s\n',cmd);  % or just step through the code
        eval(cmd);
    end 
end

The output from the above for i==1 is

command to evaluate is: rent1= landrent(i,j,Dist_lowcost)
command to evaluate is: rent1= landrent(i,j,Dist_lowcost)
command to evaluate is: rent1= landrent(i,j,Dist_lowcost)

Note that for every j , we reset rent1 to landrent(i,j,Dist_lowcost) and so that is why you are only getting three outputs - each subsequent iteration over j replaces the previous result.

If you are determined to go ahead with the above and create new variables rather than using a matrix, you could do the following instead - create the renti vector at each iteration of i and then use that as you iterate over j :

for i=1:3
    cmd = ['rent' num2str(i) '=zeros(1,3);'];
    eval(cmd);
    for j=1:3
        cmd = ['rent' num2str(i) '(j)= landrent(i,j,Dist_lowcost);'];
        fprintf('cmd=%s\n',cmd);
        eval(cmd);
    end 
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