Error in array bounds

조회 수: 1 (최근 30일)
Briette Esposito
Briette Esposito 2021년 3월 29일
답변: Arjun 2025년 6월 5일
  댓글 수: 1
Briette Esposito
Briette Esposito 2021년 3월 29일
How do I resolve this error

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

답변 (1개)

Arjun
Arjun 2025년 6월 5일
The line "row = row + 1" is incorrectly placed inside the "for" loop, which causes row to increment with every trial, not after each row is processed. This leads to an index out-of-bounds error when "row" exceeds the number of rows in "blankarray".
This example clearly illustrates the cause of the problem:
Initial Setup:
  • row = 1
  • trials(1) = 5
  • So the for loop will run: for a = 1 to 5
Inner For Loop:
  • When a = 1, row = 1. Accessing blankarray(1,cloumn) is permitted
  • When a = 2, row = 2. Accessing blankarray(2,column) is permitted
  • When a = 3, row = 3. Accessing blankarray(3,cloumn) is permitted
  • When a = 4, row = 4. Accessing blankarray(4,column) is permitted
  • When a = 5, row = 5. Accessing blankarray(5,column) is not allowed because you are trying to access 5th row which does not exist since blankarray had only 4 rows in it hence the error "Index in position 1 exceeds array bounds. Index must not exceed 4".
This error can be resolved by carefully placing the update rule "row = row + 1" ensuring that the value of "row" does not exceed the number of rows in "blankarray" when trying to access "blankarray".
One such implementation is enclosed in the following code section:
blankarray = zeros(4,6);
row = 1;
while row < 5
for a = 1:trials(row)
if x(y,a) == 1
blankarray(row,1) = blankarray(row,1) + 1;
elseif x(y,a) == 2
blankarray(row,2) = blankarray(row,2) + 1;
elseif x(y,a) == 3
blankarray(row,3) = blankarray(row,3) + 1;
elseif x(y,a) == 4
blankarray(row,4) = blankarray(row,4) + 1;
elseif x(y,a) == 5
blankarray(row,5) = blankarray(row,5) + 1;
else x(y,a) == 6;
end
end
row = row + 1; % Updating row at end of for loop.
end
I hope this helps!

카테고리

Help CenterFile Exchange에서 Data Types에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by