I try to find a general vector base for all magic squares of dimension n . Why does this program work for n = 3, but not vor n > 3?
Afficher commentaires plus anciens
The program below is supposed to find a general vector base for all magic squares of dimension n . Why does this program work for n = 3, but not vor n > 3? Any help greatly appreciated - I am afraid I am making a very stupid mistake here. Maybe I did not properly understand the usage of rref ?
Brief introduction: a magic square is an n x n matrix, where the sums in all lines, rows and the two diagonals are the same. Translating this into an quation system Mx = const you get 2*n+2 equations for n^2 variables. The solution of this (underdetermined) system is a vector space spanning all possible magic squares of dimension n. The solution of Mx = const should appear in Mind, the base matrices of the magic-square-vector-space in Mbase
function Mbase = MagicEq(n)
% identify the vector base of all magic squares of length n .
% The return values of this function are an array of matrices, M1, M2, .... where all linear combinations a*M1 + b*M2 + .... form magic squares
M = zeros(2*n+2,n^2); % initialize a matrix holding n^2 variables and 2*n + 2 constraints of the magic square of the form Mx = const
for k = 1:n
M(k,1+n*(k-1):n+n*(k-1)) = 1; % constraints on row sums
end
for k = 1:n
M(n+k,k+(0:n-1)*n) = 1; % constraints on column sums
end
M(2*n+1,(0:n-1)*n + (1:n)) = 1; % constraint for nw-se diagonal
M(2*n+2,(1:n)*n - (0:n-1)) = 1; % constraint for ne-sw diagonal
M = rref(M); % solve the equation system by computing the rref form of M
Mold = M; % just for debugging
r = rank(M);
Mind = [];
k = 1;
while ( k <= size(M,2)) % sort out all columns which are non-unit vectors
if sum(abs(M(:,k))) > 1
Mind = [Mind, -M(:,k)]; % and move them to the right side of Mx = const
M(:,k) = [];
else
k = k + 1;
end
end
Mind = [Mind(1:r,:);eye(n^2-r)]; % variables from row r+1:end are free. So add a unit matrix
for k = 1:(n^2-r)
Mbase(:,:,k) = reshape(Mind(:,k),n,n); % 'un-vectorize' the right side of the matrix equation to create the base matrices of the magic square vector space
end
Mbase(:,:,n^2-r+1) = ones(n,n); % and add the trivial magic square
end
2 commentaires
John D'Errico
le 21 Juin 2023
Modifié(e) : John D'Errico
le 21 Juin 2023
Question. If you can use rank in your code, then why would you not just use a tool like orth? Since both rank AND orth implicitly use svd, if you can use one, then surely you can use the other?
Next, your code does NOT return an array of matrices! It will return an array, where you may choose to interpret the rows or columns as vectors.
Thomas
le 22 Juin 2023
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Linear Algebra dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


