Plot variables with similar names.
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I have the following double variables and the names are
var_1
var_2
var_3
var_4
var_5
...
var_30.
I need to plot them.
I do not want to write plot(var_1), plot(var_2), plot(var_3), ..., plot(var_30).
I would like to write these codes efficient in a loop:
for i = 1 :30
plot(var_i)
end
But I do not konw how to define var_i.
Any suggestions?
1 Commento
Stephen23
il 1 Set 2020
Modificato: Stephen23
il 1 Set 2020
"I would like to write these codes efficient in a loop:"
You can't.
Because you created lots of separate variables with different names, the only ways to access them are inefficient, slow, complex, buggy, and difficult to debug. Read this to know why:
If you really want to write efficient code (also faster, simpler, neater, easier to debug code), then you would load that data into one variable, which can then be trivially accessed using simple, efficient indexing or dynamic fieldnames.
Risposte (2)
Star Strider
il 1 Set 2020
I would do something like this:
var = cat(2,var_1(:),var_2(:),var_3(:), ,var_30(:)); % Converts To Column Vectors Regardless Of Their Original Orientations & Concatenates Column-Wise, Assumes All Are The SAme Sizes
figure
hold on
for k = 1:30
plot(var(:,k))
end
hold off
grid
.
0 Commenti
Peter O
il 1 Set 2020
Are they already saved variables? If not, can you assign using a cell format instead?
The mapping would look something like:
vars{1} = var_1
vars{2} = var_2
... and so on
figure;
axes;
hold on;
for ix=1:numel(vars)
plot(vars{ix})
end
hold off
If you want to group them back in from existing:
for ix=1:30
var_id = ['var_', num2str(ix)];
vars{ix} = eval(var_id);
end
2 Commenti
Stephen23
il 1 Set 2020
"Tthese data are already saved in my data.mat."
Then you should avoid dynamic variable names and load directly into one variable. It would be much better to fix this problem at its source, rather than trying to write hack code later when you plot them.
Are the variables in one mat file, or multiple mat files?
Note to future self: do not create lots of numbered variables, they make accessing data more difficult.
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!