MATLAB Answers

0

Index exceeds the number of array elements (5)

Asked by Kolleggerm1 on 7 Oct 2019
Latest activity Commented on by the cyclist
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')

  1 Comment

Kolleggerm1's comment moved here:
So I added a line to the for-loop to identify the max of i which seemed to solve the exceeding error, but now I get an error "Array indices must be positive integers or logical values" in line 10
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
i=0:1:4;
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')

Sign in to comment.

Tags

2 Answers

Answer by the cyclist
on 7 Oct 2019
 Accepted Answer

You have initialized x and y to be vectors of length 5. But in your for loop, i reaches the value value 5, and then you try to access x(i+1), which is x(6), which does not exist. You could run your for loop over just i = 1:n-1.

  3 Comments

Thank you for your response, but when I adjusted to i=1:n-1, my x values all became 1.25 when they aren't supposed to exceed 1 (and are supposed to go up by 0.25).
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')
Screen Shot 2019-10-07 at 12.49.25 PM.png
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.


Answer by Matt J
on 7 Oct 2019

for i=1:n-1

  0 Comments

Sign in to comment.