How can I use a for loop to create new variables?

9 次查看(过去 30 天)
I am very new to MATLAB so I apologize beforehand.
I have this code here which works fine:
t = 0:0.01:10;
y_01 = exp(-0.1*t);
y_1 = exp(-1*t);
y_3 = exp(-3*t);
plot(t,y_01,t,y_1,t,y_3)
However, I was wondering if I could condense it by using a for loop to have only one line for declaring the functions to be graphed, something like this:
t = 0:0.01:10;
for a = [0.1 1 3]
y.num2str(a) = exp(-a*t);
plot(a,y.num2str(a))
end
I did read a post that said trying to implement this is not a good idea (I think that's what the gist was) but I'm not 100% sure. I understand the "pseudo-code" above wouldn't plot them all on the same plot as well.

采纳的回答

Steven Lord
Steven Lord 2020-9-30
There are many posts that say trying to create numbered variables like that is discouraged, yes.
If you want to put all those plots on the same axes, you can do this without creating the individual variables.
t = 0:0.01:10;
% Tell MATLAB not to clear the axes each time you make a new plot
hold on
for M = [0.1, 1, 3]
plot(t, exp(-M*t));
end
% Optional: the next time you plot into this axes, the existing lines will be cleared
hold off
  2 个评论
Michael McMahon
Michael McMahon 2020-9-30
编辑:Michael McMahon 2020-9-30
Thank you Steven! I keep forgetting I don't have to actually assign things in MATLAB, I can just tell it to do things with the data already present - this is much more intuitive.
Steven Lord
Steven Lord 2020-9-30
Since James Tursa added a legend I might as well add one too. Assuming you're using a release that includes the string data type, modify the plot call:
plot(t, exp(-M*t), 'DisplayName', "exp(-" + M + "*t)")
and put this at the end of the code to actually display the legend:
legend show

请先登录,再进行评论。

更多回答(1 个)

James Tursa
James Tursa 2020-9-30
编辑:James Tursa 2020-9-30
You might consider automatic array expansion. E.g., look at this result:
t = 0:0.01:10; % row
a = [0.1 1 3]'; % column
y = exp(-a.*t); % automatic array expansion since column .* row
plot(t,y)
grid on
legend(arrayfun(@(x)sprintf('a = %g',x),a,'uni',false))
title('e^-^a^t')
xlabel('t')
  1 个评论
Michael McMahon
Michael McMahon 2020-9-30
编辑:Michael McMahon 2020-9-30
I like this alternative to using a for loop, thank you James.
also the edits are helpful! Slowly learning how to make plots presentable :)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Line Plots 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by