How to debug error "Index in position 1 exceeds array bounds"?

184 visualizzazioni (ultimi 30 giorni)
I have a cell array data. The size is 3 by 9. Every cell is the array of class double. Commented section is the size of these arrays. For example,
data{1,1}
ans =
644.1262 643.0714 646.7557 647.4521 643.0392 625.5089 623.9397 633.4525 647.2367 640.6563
422.7087 422.5670 425.1260 422.5875 420.1111 436.3631 436.7513 435.9344 487.6950 500.0021
0 0.0028 0.0056 0.0083 0.0111 0.0139 0.0167 0.0194 0.0222 0.0250
0 1.0000 0 NaN NaN NaN NaN NaN NaN NaN
When I try to run the loop to check the condition and create a new cell array with some strings, I get an error "Index in position 1 exceeds array bounds".
% cellsz = cellfun(@size,data,'uni',false)
% cellsz =
% 3×9 cell array
%
% {[4 10]} {[ 4 67]} {[4 302]} {[4 302]} {[ 4 50]} {[4 319]} {[4 118]} {[4 201]} {[4 201]}
% {[4 17]} {[4 362]} {[4 109]} {[4 253]} {[4 253]} {[ 0 0]} {[ 0 0]} {[ 0 0]} {[ 0 0]}
% {[ 4 8]} {[ 4 8]} {[4 363]} {[ 4 88]} {[4 275]} {[4 275]} {[ 4 7]} {[4 364]} {[4 364]}
D = size(data);
for i = 1 : D(1)
for j = 1 : D(2)
if data{i,j}(4,1) == 1
A{j+1,2,i} = 'Exc';
elseif data{1,3}(4,2) == 1
A{j+1,2,i} = 'Well';
else
A{j+1,2,i} = 'Bad';
end
end
end
Could you please help me to figure out what array it means? Also, what is the best way to debug such errors? Is it possible to rewrite this code to run faster? Thank you very much for your time and help! I am trying to learn how to code.

Risposta accettata

Adam Danz
Adam Danz il 15 Set 2021
Modificato: Adam Danz il 15 Set 2021
> " How to debug error... "
That's the right question to ask (+1).
Knowing that there would be an error, I started by setting the pause on errors (image below).
It paused on this line below where I evaluated i and j to find that the error occurs on the first iteration of both loops.
And then I saw it 👀 data{i,j}(4,1)
data{i,j} or data{1,1} accesses the first element of the data cell array, [4 10]. Notice that this has 1 row and 2 columns but you're asking for row 4, column 1. Hence the error, "Index in position 1 exceeds array bounds".
That error would also occur in the second condition, data{1,3} since none of the cell elements contain 3 rows. Rather than guessing what your intensions are, if you describe the goal I could help get you there.
  18 Commenti
CheshireM
CheshireM il 21 Set 2021
Thank you very much for your help! I understood!

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by