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 日

0 投票

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 件のコメント

Federico Draetta
Federico Draetta 2019 年 10 月 23 日
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.
Guillaume
Guillaume 2019 年 10 月 23 日
eps is actually a function. eps returns eps(1).
KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 10 月 23 日
編集済み: KALYAN ACHARJYA 2019 年 10 月 23 日
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 日

0 投票

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 ExchangeMatrix 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