Asked by Kolleggerm1
on 7 Oct 2019

I am solving Forward Euler for dy=x*y+1, x between 0 and 1, y(0)=0 h=.25

I have gotten the error message "Index exceeds the number of array elements (5)" after rearranging the code (because I was getting other error messages). How can I clear it up?

clc; clear all;

h=0.25; % step size

xmin=0;

xmax=1;

x=xmin:h:xmax; %x boundaries

n=length(x);

y=zeros(1,n);% Initial condition

for i=1:n

x0=0;

dy=(x(i+1)*y(i)+1);

x(i+1)=n*h;

y(i+1)=y(i)+h*dy;

end

figure(1)

hold on

plot (y,x,'b', 'linewidth',2)

title ('Forward Euler')

Answer by the cyclist
on 7 Oct 2019

Accepted Answer

Kolleggerm1
on 7 Oct 2019

the cyclist
on 7 Oct 2019

The endpoint of your loop has nothing to do with that. Your values of x are all 1.25 because

x(i+1)=n*h

is always evaluated to 1.25. Maybe you meant

x(i+1)=i*h

?

So, fixing both of those things, you would have

clc; clear all;

h=0.25; % step size

xmin=0;

xmax=1;

x=xmin:h:xmax; %x boundaries

n=length(x);

y=zeros(1,n);% Initial condition

x0=0;

for i=1:n-1

dy=(x(i+1)*y(i)+1);

x(i+1)=i*h

y(i+1)=y(i)+h*dy

end

figure

hold on

plot (y,x,'b', 'linewidth',2)

title ('Forward Euler')

the cyclist
on 7 Oct 2019

Also ... did you intend to plot x on the vertical axis? If not, then

plot(x,y,'b','linewidth',2)

instead.

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Matt J (view profile)

## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/484021-index-exceeds-the-number-of-array-elements-5#comment_753538

Sign in to comment.