Error in array bounds

1 Ansicht (letzte 30 Tage)
Briette Esposito
Briette Esposito am 29 Mär. 2021
Beantwortet: Arjun am 5 Jun. 2025
  1 Kommentar
Briette Esposito
Briette Esposito am 29 Mär. 2021
How do I resolve this error

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Arjun
Arjun am 5 Jun. 2025
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!

Kategorien

Mehr zu Data Types finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by