Write a script for Matlab that creates a magic square matrix
Write a script for Matlab that creates a magic square matrix but can not use the magic square function. has to be a for loop that makes a magic square.
Solution
proc iml; start Magic(n); /* Moler\'s algorithm for constructing a magic square for any n. See Moler, C. (2011) \"Magic Square,\" Chapter 10 in Experiments with MATLAB, p. 7-10 E-Book: http://www.mathworks.com/moler/exm/chapters/magic.pdf */ /* define helper functions */ start ModPos(a, q); /* always return positive value for mod(a,q) */ return( a - q*floor(a/q) ); finish; /* Magic square when n is odd */ start MagicOdd(n); I = repeat( T(1:n), 1, n ); J = repeat( 1:n, n ); /* or T(I) */ A = ModPos(I+J-(n+3)/2, n); /* modify formula to match MATLAB output */ B = mod(I+2*J-2, n); return( n*A + B + 1 ); finish; /* Magic square when n is a multiple of 4 */ start Magic4(n); M = shape(1:n##2, n, n); I = repeat( T(1:n), 1, n ); J = repeat( 1:n, n ); /* or T(I) */ idx = loc(floor(mod(I,4)/2) = floor(mod(J,4)/2)); M[idx] = n##2 + 1 - M[idx]; return( M ); finish; /* Magic square when n>4 is even but not a multiple of 4 */ start Magic2(n); s = n/2; /* s is odd */ A = MagicOdd(s); M = (A || (A + 2*s##2)) // /* 2x2 blocks of magic squares */ ((A+3*s##2) || (A + s##2)); /* col sums are correct; permute within cols to adjust row sums */ i = 1:s; r = (n-2)/4; h = do(n-r+2,n,1); /* might be empty */ j = (1:r) || h; M[i || i+s, j] = M[i+s || i, j]; /* swap rows for cols in j */ i = r+1; j = 1 || i; M[i || i+s, j] = M[i+s || i, j]; /* swap rows for cols in j */ return( M ); finish; /* main algorithm */ if n<=1 then return(1); if n=2 then return( {. ., . .} ); /* no magic square exists */ if mod(n,2)=1 then return( MagicOdd(n) ); /* n is odd */ if mod(n,4)=0 then return( Magic4(n) ); /* n is divisible by 4 */ return( Magic2(n) ); /* n is divisible by 2, but not by 4 */ finish;