Getting the error. "index exceeds the number of array elements".

조회 수: 2 (최근 30일)
AVINASH SAHU
AVINASH SAHU 2022년 7월 30일
댓글: AVINASH SAHU 2022년 7월 30일
a =2;
ndiv = 100;
x = linspace(0,1,ndiv);
dx = x(2)-x(1);
for i = 2: (ndiv-1)
h(i) = a - (a-1)*x(i);
dh = (h(i+1)-h(i-1))/(2*dx);
end
Index exceeds the number of array elements. Index must not exceed 2.

채택된 답변

Steven Lord
Steven Lord 2022년 7월 30일
When i is 2, you assign to h(2) but then on the next line you attempt to access h(3). That element doesn't exist yet.
I suggest moving the second line of your loop to after the loop and removing its dependence on the loop variable.
x = (1:10).^2
x = 1×10
1 4 9 16 25 36 49 64 81 100
y = x(2:end)+x(1:end-1)
y = 1×9
5 13 25 41 61 85 113 145 181
Note that y has one fewer element than x does, so you'll need to handle the edges.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by