function [ismag, whynot] = ismagic(square) % function [ismag, whynot] = ismagic(square) % square: square to be checked for "magicness" % ismag: 1 if magical, 0 if not % whynot: if ismag == 0, then % whynot returns the reason why ismagic fails % whynot = 1 : not all elements from 1 to n^2 uniquely used. % = 2 : not all rows and columns add up to the same number dim = size(square,1); elems = unique(square); nelems = length(elems); if ( ~(elems(1) == 1 & elems(nelems) == nelems & nelems == size(square,1)^2) ) whynot = 1; ismag = 0; return; end colsums = unique(sum(square,1)); rowsums = unique(sum(square,2)); diagsums = unique([sum(diag(square)), sum(diag(rot90(square)))]); if ( ~(length(colsums) == 1 & length(rowsums) == 1 & length(diagsums) == 1) ) whynot = 2; ismag = 0; return; end if ( ~(colsums == rowsums & colsums == diagsums) ) whynot = 2; ismag = 0; return; end ismag = 1; whynot = []; return;