0
サイズがnのmatlabにzeros()コマンドで初期化された魔方陣の関数を作成し、iterator iを使ってforループを作成しました。Matlabのマジックスクエア用関数を作成
出力が正しくなっていますが、行と列の両方に対して対角線上の場所が外れている場合の問題を解決する方法がわかりません。行あれば魔方陣(5)、この数は、16
magicsqure(5)
マトリックス=
0 0 1 8 15
0 5 7 14 0
4 6 13 0 0
10 12 0 0 3
11 0 0 2 9
%
function output = magicsquare(n)
% initialize with zeros() function
matrix = zeros(n);
% place first number
col = (n-1)/2 + 1; % first number of magic square starts in the middle of top row
row = 1; % top row
% for loop with iterator i
for i = 1:(n^2) % start with 1 up to n^2 (perfect square of n sized matrix)
% if filled, move down on from original
if(matrix(row, col) ~= 0) % if a space in square is filled ...
row = row + 2; % ... move down 2 rows ...
col = col - 1; % ... and 1 column to the left
end
% up one, right one
matrix(row, col) = i % input i at matrix(a,b) position
row = row - 1; % move up one row
col = col + 1; % move right one column
% out of matrix space -- wrap matrix
if col < 1 % if column goes to left of col 1
col = n; % go to right most column
end
if row > (n+1) % if row goes down past last row by more than one space
row = 2; % go to second row
end
if row > n % does not exist by one space
row = 1; % go to first row
end
if col > n
col = 1; % go to left most column
end
if row < 1
row = n; % go to last row
end
if row < 1 && col > n %!! TROUBLESHOOTING
row = 2;
col = n;
end
output = matrix; % print the magic square