How can I use a for loop to create new variables?
Show older comments
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.
Accepted Answer
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')
1 Comment
Michael McMahon
on 30 Sep 2020
Edited: Michael McMahon
on 30 Sep 2020
Categories
Find more on Performance and Memory 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!