Index exceeds matrix dimensions error?
Ältere Kommentare anzeigen
Hello everyone, my code is giving me the error "Index exceeds matrix dimensions. Error in queens (line 11). if test_board(row,col) == 0"
Im trying to attempt backtracking but cant even get passed looping through my array to place queens because of this error.
Any help would be appreciated, thanks!
function [queens] = queens(size)
test_board = zeros(size,size);
final_board = zeros(size,size);
row = 1; col = 1;
queen_counter = 0;
%Loop until "size" number of queens have been successfully placed
while (queen_counter < size)
%Find first safe space and place queen
if test_board(row,col) == 0
test_board(row,col) = 1;
final_board(row,col) = 1;
%Attacking the row and column in which the queen was placed
test_board(:,col) = 8;
test_board(row,:) = 8;
%Iterate through using temporary variables to keep real
%row and column element in place
temp_row = row;
temp_col = col;
%Attacking lower diagonal
while (temp_col < size && temp_row < size)
temp_row = temp_row + 1;
temp_col = temp_col + 1;
test_board(temp_row,temp_col) = 8;
end
temp_row = row;
temp_col = col;
%Attacking lower diagonal
while (temp_col < size && temp_row > 1)
temp_row = temp_row - 1;
temp_col = temp_col + 1;
test_board(temp_row,temp_col) = 8;
end
%Move to next column after successful queen placement
col = col + 1;
queen_counter = queen_counter + 1;
%Move down one in column if first space isn't safe
else
row = row + 1;
end
end
disp(test_board); disp(final_board);
end
Antworten (1)
Image Analyst
am 20 Sep. 2017
0 Stimmen
DO NOT use size as the name of your variable. It's the name of a vitally important built-in function, that you just overwrote.
Whatever you passed in for size, in your loop either row or column is greater than that, so it throws an error.
Kategorien
Mehr zu Matrix Indexing finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!