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

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

답변 (2개)

KALYAN ACHARJYA
KALYAN ACHARJYA 2019년 10월 23일
편집: KALYAN ACHARJYA 2019년 10월 23일
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

eps is an already defined variable by matlab and it's the minimum value matlab can deal with. I'm trying to enforce convergence to understand which is the first value y(k+1) such that y(k+1)-y(k) is less than eps, and so the y function can be considered constant.
eps is actually a function. eps returns eps(1).
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

댓글을 달려면 로그인하십시오.

Guillaume
Guillaume 2019년 10월 23일
편집: Guillaume 2019년 10월 23일
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.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

질문:

2019년 10월 23일

편집:

2019년 10월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by