Why is my code returning the error "Index in position 1 exceeds array bounds" when calling adjacent()?

1 次查看(过去 30 天)
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;

采纳的回答

Walter Roberson
Walter Roberson 2025-8-2
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 个评论

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

产品


版本

R2025a

Community Treasure Hunt

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

Start Hunting!

Translated by