How to plot multiple functions with a for loop

12 次查看(过去 30 天)
Hello, I am trying to use a for loop to solve an ODE by way of Euler's method. I have a loop that works for a single step size h = 0.05, but I was wondering if I can get the loop to run with h = [0.05 0.1 0.2], and then plot the three different outputs? Here is the code that I have so far, loops confuse me so any help is greatly appreciated.
y0 = 0;
t0 = 0;
tf = 1;
h = 0.05;
f = @(t,y) y^2 + 1;
y = y0;
y_1 = y;
for t = t0:h:tf-h
yp = f(t,y);
y = y + h*yp;
y_1 = [y_1 ; y];
end
x = 0:h:1;
plot(x,y_1)

采纳的回答

Ameer Hamza
Ameer Hamza 2020-5-26
编辑:Ameer Hamza 2020-5-26
H = [0.05 0.1 0.2];
figure;
hold on
for i=1:numel(H)
y0 = 0;
t0 = 0;
tf = 1;
h = H(i);
f = @(t,y) y^2 + 1;
y = y0;
y_1 = y;
for t = t0:h:tf-h
yp = f(t,y);
y = y + h*yp;
y_1 = [y_1 ; y];
end
x = 0:h:1;
plot(x,y_1, 'DisplayName', ['H = ' num2str(H(i))])
end
legend
  1 个评论
Travis Girton
Travis Girton 2020-5-26
Thank you, I was trying something simular to this but with both loops later in the code and couldn't get it to work. Starting the loop much earlier makes sense now that I see it.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Ordinary Differential Equations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by