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 Center および File ExchangeWorkspace 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