How can I use a for loop to create new variables?
4 views (last 30 days)
Show older comments
Michael McMahon
on 30 Sep 2020
Edited: Michael McMahon
on 30 Sep 2020
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.
0 Comments
Accepted Answer
Steven Lord
on 30 Sep 2020
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 Comments
Steven Lord
on 30 Sep 2020
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
More Answers (1)
James Tursa
on 30 Sep 2020
Edited: James Tursa
on 30 Sep 2020
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')
See Also
Categories
Find more on Line Plots in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!