- #1
cookiemnstr510510
- 162
- 14
- Homework Statement
- Code euler method for solving ODE in matlab
- Relevant Equations
- test case given: y0=10, f=@(t,y) -0.5*y
The test case for the block of code below is:
y0=10,
f=@(t,y) -0.5*y,
[t,y]=euler_method_attempt(f,0,5,y0,10)
This code below works and is the correct answer, but I am confused on some parts of it. When indexing the for loop it seems as if the first output for "y" would be y(2), not y(1). And as far as the math goes I think y(2)=7.5.
I also don't understand why we wouldn't write something like:
for i=0:length(t)...
So how does MATLAB access the first element of "y"?
Thanks so much!
y0=10,
f=@(t,y) -0.5*y,
[t,y]=euler_method_attempt(f,0,5,y0,10)
This code below works and is the correct answer, but I am confused on some parts of it. When indexing the for loop it seems as if the first output for "y" would be y(2), not y(1). And as far as the math goes I think y(2)=7.5.
I also don't understand why we wouldn't write something like:
for i=0:length(t)...
So how does MATLAB access the first element of "y"?
Thanks so much!
Matlab:
function [t,y]=euler_method_attempt(f,t0,tf,y0,n)
t=linspace(t0,tf,n+1);
dt=t(2)-t(1);
y=[y0,zeros(1,n)];
for i=1:length(t)-1
y(i+1) = f(t(i),y(i)).*dt +y(i);
end
end