Plot variables with similar names.
4 次查看(过去 30 天)
显示 更早的评论
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
2020-9-1
编辑:Stephen23
2020-9-1
"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.
回答(2 个)
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
.
0 个评论
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 个评论
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 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!