Error Index exceeds the number of array elements (151).

1 view (last 30 days)
I can't understand why matlab keeps enlarging k at each cicle so i can't use the while loop.
x = 0:1:150;
y = x+1;
k=1;
while y(k+1)-y(k)>eps
k=k+1;
end

Answers (2)

KALYAN ACHARJYA
KALYAN ACHARJYA on 23 Oct 2019
Edited: KALYAN ACHARJYA on 23 Oct 2019
Define eps??
Also ensure that the while loop iteration should not exceeded the length(x)-1
Also,
This value in the while loop condition always provides constant value of 1
y(k+1)-y(k)
If Once the loop will true, it will true for all
Or Is this way you are looking for to avoid the Error Index exceeds the number of array elements
x=0:1:150;
y=x+1
k=1;
eps=0.6; % Just I have choosen
while y(k+1)-y(k)>eps && k<length(x)-1
k=k+1;
end
I have no idea what you are trying to do, as inside loop, there are no statements apart from k=k+1;
  3 Comments
KALYAN ACHARJYA
KALYAN ACHARJYA on 23 Oct 2019
Edited: KALYAN ACHARJYA on 23 Oct 2019
Thnaks @Guillaume Yes, Federico Draetta but if you try with y(k+1)-y(k) gives constant 1 in the example case as given by you, then if true, then it runs till length(x)-1
See example
x=0:1:150;
y=x+1;
k=1;
while y(k+1)-y(k)>eps && k<length(x)-1
k=k+1
end

Sign in to comment.


Guillaume
Guillaume on 23 Oct 2019
Edited: Guillaume on 23 Oct 2019
You define x as a vector of 151 elements: integers from 0 to 150, then you do:
y = x+1;
This defines y as a matrix the same size as x where each element is the same as the corresponding element of x but incremented by 1. Thus y is a vector of 151 elements: the integers from 1 to 151.
Then you test if y(k+1) - y(k) is greater than eps, eps(1) to be precise, which is around 2e-16. So you're basically comparing the difference between two consecutive elements of y, which as established are consecutive integers. Well, you don't need to ask matlab what that is. The difference is always 1. it's always much greater than eps(1). As a result your k will increase forever. However, at some point you're asking matlab to calculate y(152)-y(151) but y(152) doesn't exist. Matlab won't invent it for you, so it errors with index exceeds matrix dimension.
It's unclear what you were attempting to do, but whatever that was, your loop certainly doesn't do it.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!