The MATLAB function magicN constructs an magic square magic
The MATLAB function magic(N) constructs an magic square.
>> magic(3) ans = 8 1 6 3 5 7 4 9 2
The “magical” property of a magic square is that it contains the integers 1 to exactly once each and every row, column, and diagonal has the same sum:
8+1+6=15 3+5+7=15 4+9+2=15 8+3+4=15 1+5+9=15 6+7+2=15 8+5+2=15 6+5+4=15
Now it’s your turn. Write a function (verify_magic.m) that that take as input a square matrix and computes the sum of each row, column, and diagonal of the matrix to determine whether the input is a magic square. If the input is not a square matrix, use the error function to display an error message and abort the function. The output of the function should be a logical value indicating whether or not the input is a magic square: logical true for a magic square, logical false for a muggle square.
Example: >> verify_magic(magic(3)) ans = 1
>> verify_magic([1 2 3 ; 4 5 6 ; 7 8 9]) ans = 0
Solution
function isMagicSquare = verify_magic(squareMatrix)
if nargin ~= 1
error(\'Number of input arguments should be exactly one! \');
elseif size(squareMatrix,1) ~= size(squareMatrix,2)
error(\'Input is not a square matrix! \')
else
% side length
rows = size(squareMatrix,1);
% Assume it is a magic square in the beginning
% Now check the if it contains integers 1 to N^2 exactly once
% Initialize an empty logical array with N^2 length
numCheck = false(1,rows ^ 2);
% Iterate through the matrix (Column array to row array)
for i = squareMatrix(:)\'
if i <= 0 || i > rows^2 % Not in range, exit loop
break;
elseif numCheck(i) % Already marked true, repeated
break;
else
numCheck(i) = true; % Mark it as true
end
end
% if all is marked true then isMagicSquare remain true for now
isMagicSquare = all(numCheck);
% Now check the sum of rows, columns and diagnoals equal
if isMagicSquare % If already false, then don\'t need the step
% Sum array of all rows and columns
sumRows = sum(squareMatrix,1);
sumCols = sum(squareMatrix,2)\'; % Column vector to row vector
% Sum of two diagnoals
sumDiags1 = 0;
sumDiags2 = 0;
for i = 1:rows
sumDiags1 = sumDiags1 + squareMatrix(i,i);
sumDiags2 = sumDiags2 + squareMatrix(rows-i+1, i);
end
% Check, in sequence:
% - Two diagnoals have the same sumRows
% - The row sums all equal to diagnoal sum
% - The column sums all equals to diagnoal sum
if ~all([sumDiags1 == sumDiags2, sumRows == sumDiags1, sumCols == sumDiags1])
isMagicSquare = false;
end
end
end
end

