Plot variables with similar names.

조회 수: 10 (최근 30일)
Yufei Cao
Yufei Cao 2020년 9월 1일
편집: Stephen23 2020년 9월 1일
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
Stephen23
Stephen23 2020년 9월 1일
편집: Stephen23 2020년 9월 1일
"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.

댓글을 달려면 로그인하십시오.

답변 (2개)

Star Strider
Star Strider 2020년 9월 1일
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 2020년 9월 1일
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
Yufei Cao
Yufei Cao 2020년 9월 1일
Hi, Peter, Thanks. Tthese data are already saved in my data.mat.
Stephen23
Stephen23 2020년 9월 1일
"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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Workspace Variables and MAT-Files에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by