Azzera filtri
Azzera filtri

Error: Index in position 2 exceeds array bounds.

1 visualizzazione (ultimi 30 giorni)
lil brain
lil brain il 15 Mag 2023
Risposto: Cris LaPierre il 15 Mag 2023
Hi,
I have a loop that loops over the cells in "balls_xyz". If the loop encounters a cell that is empty it is supposed to skip that cell. However, when I run the code:
distances_balls_right = cell(size(balls_xyz)); % preallocate the distances cell array
distances_balls_left = cell(size(balls_xyz)); % preallocate the distances cell array
for i = 1:numel(balls_xyz)
if isempty(balls_xyz(i))
continue; % skip empty cells
end
this_cell = cell2mat(balls_xyz(i));
right_hand = sqrt((this_cell(:,7)-this_cell(:,1)).^2 + (this_cell(:,8)-this_cell(:,2)).^2 + (this_cell(:,9)-this_cell(:,3)).^2);
left_hand = sqrt((this_cell(:,7)-this_cell(:,4)).^2 + (this_cell(:,8)-this_cell(:,5)).^2 + (this_cell(:,9)-this_cell(:,6)).^2);
distances_balls_right{i} = right_hand;
distances_balls_left{i} = left_hand;
end
I get the error:
Index in position 2 exceeds array bounds.
right_hand = sqrt((this_cell(:,7)-this_cell(:,1)).^2 + (this_cell(:,8)-this_cell(:,2)).^2 + (this_cell(:,9)-this_cell(:,3)).^2);
Thanks!

Risposte (1)

Cris LaPierre
Cris LaPierre il 15 Mag 2023
The problem is that your variable this_cell does not appear to have the number of columns that your code expects it to have. So it is not empty, but also not the expected size. The rest of your error message should be telling you the actual number of columns.
% Create a variable with 2 columns
A = rand(2)
A = 2×2
0.8845 0.4202 0.9545 0.7936
% Your error, caused by indexing the 3rd column, which doesn't exist
A(:,3)
Index in position 2 exceeds array bounds. Index must not exceed 2.

Community Treasure Hunt

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

Start Hunting!

Translated by