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
Walter Roberson
Walter Roberson 2025년 8월 3일
You should also consider moving the 403006 to the last dimension; it will be more efficient.

댓글을 달려면 로그인하십시오.

추가 답변 (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