Why is my code returning the error "Index in position 1 exceeds array bounds" when calling adjacent()?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Ian
le 2 Août 2025
Commenté : Walter Roberson
le 3 Août 2025
I have the following snippet of code that yields the error "Index in position 1 exceeds array bounds" when calling the function adjacent():
function out = polycubes()
% Yields array of polycubes of orders 1-10 which fit within a 3x3x3 cube
% Input: none
% Output: array of all polycubes of orders 1-10 which fit within a 3x3x3
% cube
pCubes = zeros(403006,3,3,3);
% Initializes start cube
pCubes(1,:,:,1) = zeros(3,3);
pCubes(1,:,:,2) = [0 0 0; 0 1 0; 0 0 0];
pCubes(1,:,:,3) = zeros(3,3);
% Starts master counter
pCubeIndex = 1;
while true
% Checks if polycube contains 10 cubes. If not, moves to next polycube
% to be built upon
if sum(pCubes(pCubeIndex,:,:,:),"all") == 10
pCubeIndex = pCubeIndex + 1;
if mod(pCubeIndex,1000) == 0
disp("Cube ", pCubeIndex, ": ", pCubes(pCubeIndex));
end
% Breaks if no polycubes less than order 10 remain to be built upon
elseif sum(pCubes(pCubeIndex,:,:,:),"all") == 0
if mod(pCubeIndex,1000) == 0
disp("Cube ", pCubeIndex, ": ", pCubes(pCubeIndex));
end
break
else
% Creates list of cells adjacent to existing cubes in a polycube
adjCells = zeros(26,3);
counter = 0;
for a = 1:3
for b = 1:3
for c = 1:3
if a ~= 2 | b ~= 2 | c ~= 2
if pCubes(pCubeIndex,a,b,c) == 0
if adjacent(pCubes(1,:,:,:),a,b,c) % error here
adjCells(counter,:) = [a b c];
counter = counter + 1;
end
end
end
end
end
end
end
end
Here is the entire code for adjacent():
function out = adjacent(cube,x,y,z)
output = false;
if x + 1 <= 3
if cube(x+1,y,z) ~= 0
output = true;
end
end
if x - 1 >= 1
if cube(x-1,y,z) ~= 0
output = true;
end
end
if y + 1 <= 3
if cube(x,y+1,z) ~= 0
output = true;
end
end
if y - 1 >= 1
if cube(x,y-1,z) ~= 0
output = true;
end
end
if z + 1 <= 3
if cube(x,y,z+1) ~= 0
output = true;
end
end
if z - 1 >= 1
if cube(x,y,z-1) ~= 0
output = true;
end
end
out = output;
0 commentaires
Réponse acceptée
Walter Roberson
le 2 Août 2025
if adjacent(pCubes(1,:,:,:),a,b,c) % error here
You are passing in a 1 x something x something by something array
if cube(x+1,y,z) ~= 0
You are addressing it as a something by something by something array, forgetting that the leading dimension of it is 1
3 commentaires
Stephen23
le 3 Août 2025
If you want to write fragile code: https://www.mathworks.com/help/matlab/ref/squeeze.html
If you want to write robust code: https://www.mathworks.com/help/matlab/ref/double.permute.html
Walter Roberson
le 3 Août 2025
You should also consider moving the 403006 to the last dimension; it will be more efficient.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!