Reputation: 975
In MATLAB, I have following output of data from a script:
A1 = [1 2;3 4]
A2 = [2 2; 4 5]
A3 = [3 5; 7 8]
I need to create a for loop to step through the each variable and plot. Something like:
for i = 1:3
plot(A(i))
end
So A1 will generate a plot. A2 will generate a plot. And A3 will generate a plot.
Thanks
Upvotes: 0
Views: 1000
Reputation: 83457
Loop using eval
(will emulate variable variable) and figure
(will create a figure for each A):
A1 = [1 2;3 4];
A2 = [2 2; 4 5];
A3 = [3 5; 7 8];
for i = 1:3
figure(i);
eval(['plot(A' num2str(i) ');'])
end
If you have many As you might want to save the plots automatically, by inserting the following line right after the eval line in the loop:
print('-dpng','-r100',['A' int2str(i)])
Upvotes: 1
Reputation: 45762
I suggest you alter the script that outputs those variables to rather stick them in a cell array or a struct.
If that's not possible then if there are only 3 I would suggest you stick them in a cell array manually i.e. A{1} = A1; A{2} = A2; A{3} = A3
Only if you really really can't do either of those, you should consider using eval
for ii = 1:n
eval(['plot(A', num2str(ii), ')']);
end
to debug I suggest replacing eval
with disp
to make sure you are generating the right code
Upvotes: 5
Reputation: 114976
What you can do is use eval
for ii = 1:3
cmd = sprintf('plot( A%d );', ii );
eval( cmd );
end
However, using eval
is not recommended. The best way is if you can alter the code generating A1
...A3
, so it can either create a cell array A{1}
,...A{3}
, or even struct fields S.A1
,...,S.A3
.
Upvotes: 5