Reputation: 1
function yout = eulermethod(myeuler, t0, h, tf, y0)
tic
yout = y0
y = yout;
for t = t0 : h : tf
s = myeuler(t,y);
y = y + h*s;
y = y(2)
yout = [yout; y]
plot(t,yout)
toc
end
end
Igot this error Index in position 1 is invalid. Array indices must be positive integers or logical values.
Error in eulermethod (line 9) s = myeuler(t,y
Upvotes: 0
Views: 135
Reputation: 86
The issue here is that MATLAB thinks myeuler
is a matrix rather than a function. When you call eulermethod
, I assume you are doing something like
yout = eulermethod(myeuler, t0, h, tf, y0);
What you actually want to be doing is
yout = eulermethod(@myeuler, t0, h, tf, y0);
The @ turns the first argument into a function handle (see the matlab documentation).
There are other issues with the rest of the code but I'm not exactly sure what equation you're trying to solve so I can't help too much. Certainly, your plot line doesn't make much sense as t
is a scalar.
Assuming you're solving the differential equation dy/dt = 2y, for y(t=0) = y0, your functions should look a bit like
function dydt = myeuler(t,y)
dydt = 2*y;
end
function yout = eulermethod(myeuler, t0, h, tf, y0)
yout = y0;
y = y0;
for t = (t0+h):h:tf
s = myeuler(t,y);
y = y + h*s;
yout = [yout; y];
plot(t0:h:t, yout)
xlabel('t');
ylabel('y');
pause(0.1);
end
end
And would then be called by some code like
t0 = 0;
h = 0.01;
tf = 1;
y0 = 1.0;
yout = eulermethod(@myeuler, t0, h, tf, y0);
Upvotes: 1