Plot variables with similar names.

10 visualizaciones (últimos 30 días)
Yufei Cao
Yufei Cao el 1 de Sept. de 2020
Editada: Stephen23 el 1 de Sept. de 2020
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 comentario
Stephen23
Stephen23 el 1 de Sept. de 2020
Editada: Stephen23 el 1 de Sept. de 2020
"I would like to write these codes efficient in a loop:"
You can't.
Your anti-pattern data design means that you cannot write efficient code to access those variables.
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.

Iniciar sesión para comentar.

Respuestas (2)

Star Strider
Star Strider el 1 de Sept. de 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
.

Peter O
Peter O el 1 de Sept. de 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 comentarios
Yufei Cao
Yufei Cao el 1 de Sept. de 2020
Hi, Peter, Thanks. Tthese data are already saved in my data.mat.
Stephen23
Stephen23 el 1 de Sept. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Workspace Variables and MAT-Files en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by