MATLAB Answers

How to use For Loop to plot multiple graphs?

50 views (last 30 days)
Neilton Felipe Santos
Neilton Felipe Santos on 31 Oct 2020
Answered: Dave B on 4 Nov 2020
I have 25 tables, and I want to plot them all in distinct graphs. Each table has the name 'Freqnumber'. I tried this but it didnt work
I want it to plot the table Freq1, then Freq2, Freq3... and change the title for each iteration. What am I missing? ('Tempo','Z' and 'XL' are columns)
s = 25
for c = 1:s
plot('Freq'c.Tempo, 'Freq'c.Z,'b-')
hold on;
plot('Freq'c.Tempo, 'Freq'c.XL,'r-')
title ('Frequência'c)
xlabel('tempo')
ylabel('Impedância')
legend({'Z','XL'},'Location','southeast')
end

  2 Comments

Adam Danz
Adam Danz on 31 Oct 2020
"it didnt work" -- tells us very little.
You likely received error messages which should be included in the question.
The first error I see is,
plot('Freq'c.Tempo, 'Freq'c.Z,'b-')
^^^^^^^^^^^^^ ^^^^^^^^^
This isn't Matlab syntax.
Learn how to index Tables here,
If you need more help please be clear about the table names and the column names that you're plotting.
Neilton Felipe Santos
Neilton Felipe Santos on 31 Oct 2020
My columns are: Tempo, Z and XL
My table names are: Freq1, Freq2, Freq3, Freq4...
I tried and it worked
plot(Freq1.tempo, Freq1.Z)
but i thought that maybe has a way to iterate that number so i dont have code it 25 times:
plot(Freq1.tempo, Freq1.Z);
plot(Freq2.tempo, Freq2.Z);
plot(Freq3.tempo, Freq3.Z);
...

Sign in to comment.

Answers (1)

Dave B
Dave B on 4 Nov 2020
Neilton:
It sounds like you want to call plot on several variables (your table names), and those names vary in a systematic way. You can do this with the eval function, but this isn't generally a recommended approach. There's some detail about why not here. The code that would do this might look something like:
eval(['plot(Freq' num2str(c) '.tempo, Freq' num2str(c) '.Z)'])
You can think of the eval strategy as creating a character vector and then parsing that as if it were code in your script.
If you're in control of the code that makes these variables, you might consider putting all of those tables in a cell array. That makes it much easier to iterate (for plot, but also for anything else).
a={table(rand(10,1)) table(rand(10,1)) table(rand(10,1))};
for i = 1:numel(a)
plot(a{i}.Var1)
hold on
end
Perhaps even better is thinking about a data structure that allows all frequencies in one table. Though it's hard to guess without knowing what that might be, perhaps Freq would do well as a column in your table rather than a table for each Freq? Just a thought!

  0 Comments

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!