0

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

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

1

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)])

3 Comments

@user1608954 I strongly recommend against using eval and rather adjusting your script to make a cell matrix A such that A{1} == A1 etc... using eval is opening yourself up to a world of error, it's difficult to debug, difficult to read and difficult to maintain.
+1 for showing the use of figure() though, both other answers forgot to include it.
in addition to what @Dan said: it's also not very 'Matlab'-ish to use A1, A2, A3 and not A{1}, A{2}, A{3}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.