0

I'm trying to implement the forward Euler method using matlab, but don't understand the error I'm getting. This is what I have written:

function y = ForwardEulerMethod(f,y0,T,N)
h=T/N;
t=zeros(N+1,1);
for i=0:N
    t(i)=i.*h; %line 5
end
y=zeros(N+1,1);
y(0)=y0;
for i=1:N
    y(i)=y(i-1)+h.*f(t(i-1),y(i-1));
end
end 

My error is with line 5 and says, "Subscript indices must either be real positive integers or logicals." I am familiar with this rule, but don't see how I'm breaking it. I'm just trying to replace a zero at each location in t with a numerical value. What am I missing?

Matt Robbins
  • 429
  • 2
  • 5
  • 10
  • 2
    when i==1 y(i-1)=0. You should start the loop from 1=2 – shamalaia Apr 16 '18 at 01:43
  • 1
    Possible duplicate of [Subscript indices must either be real positive integers or logicals, generic solution](https://stackoverflow.com/questions/20054047/subscript-indices-must-either-be-real-positive-integers-or-logicals-generic-sol) – vijoc Apr 16 '18 at 06:16
  • The error is pretty clear and you must only read it and use the debugger if it's not clear enough. Also use the "Stop on error" option is useful that breaks automatically on errors. – Jepessen Apr 16 '18 at 07:07

2 Answers2

0

You're iterating over i = 0:N and using it as t(i)=i.*h, so you're trying to access t(0) during the first iteration. Matlab indexing starts from 1, hence the error.

You also have other lines which will cause the same error, once the execution gets that far.

vijoc
  • 683
  • 8
  • 17
0

Agree with @vijoc above. You are indexing with 0 at multiple places. You could either change how you are indexing the values or get rid of the for loop altogether, like below:

function y = ForwardEulerMethod(f,y0,T,N)
h=T/N;
t=0:N .* h; % this takes the place of the first for-loop
y=zeros(N+1,1);
y(1)=y0;
for i=2:N+1
    y(i)=y(i-1)+h.*f(t(i-1),y(i-1));
end
end

You could even replace the second loop if the function f takes vector inputs like so:

y(1) = y0;
y(2:end) = y(1:end-1) + h .* f(t(1:end-1), y(1:end-1));
ammportal
  • 991
  • 1
  • 11
  • 27