MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today**New to MATLAB?**

Asked by redcavalry
on 28 Sep 2011

Write a MATLAB code that creates Magic Square of user defined odd order(for example, 5x5, 7x7, etc.) using Terrace method

1. Calculates elements of the Magic Square. 2. Displays the Magic Square.

Note : you can use the special fuction magic to test your own fuction only

M=zeros(n,n); row=1; column=(n+1)/2;

for k=1:n^2 M(row,column)=k; row=row-1; column=column+1; if(row==0 && column<=n) row=n; elseif(row>0 && column>n) column=1; elseif((row==0 && column>n) || M(row,column)>0 ) row=row+2; column=column-1; end end

*No products are associated with this question.*

Answer by the cyclist
on 28 Sep 2011

I see that you have calculated the elements of the magic square (which look correct to me), but I do not see that you have displayed the magic square.

Answer by Daniel
on 28 Sep 2011

you might want to try

type magic

TMW do it in 4 lines.

the cyclist
on 28 Sep 2011

Guessing that TMW doesn't use the "terrace method", but have to admit that I don't know for sure.

Walter Roberson
on 28 Sep 2011

TMW needs 11 lines for the "singly even" case, at least in R2008b.

(Singly even is a size which is of the form 4*K+2 for non-negative integers K.)

Answer by Image Analyst
on 28 Sep 2011

You can determine if your code is correct by subtracting your M from the correct answer. If everything is zero then you matched the correct magic square.

M % Display M result = M - magic(n) % Display difference

Answer by Andrei Bobrov
on 29 Sep 2011

testing your code *(edited)*

all(diff([sum(M),sum(M,2)',sum(diag(M)),sum(diag(M(:,end:-1:1)))])==0) &&... isequal(sort(M(:)'),1:numel(M))

ADDED

Hi redcavalry! You used siamese method. Terrace method is variant of siamese method. About of Terrace method in russian Wikipedia (see "Метод террас").

Cod: 1 variant (eg,for n = 5)

n = 5; k = n*2-1; B = zeros(k); B(1:2:end) = 1; a = hankel(1:k,k:-1:1); B = (min(a,a(:,end:-1:1))>=n&B)+0; A = zeros(n,k); A(:,1:2:end) = 1; A(~~A)=1:n^2; A = reshape(A,k,[])'; B(~~B)=A(~~A); i1 = [(n+1)/2:n-1,n+1:n+(n-1)/2]; i2 = [i1(end)+1:k,1:i1(1)-1]; B(:,i1) = B(:,i1) + B(:,i2); B(i1,:) = B(i1,:) + B(i2,:); M = B(i1(1):i1(end),i1(1):i1(end))

2 variant with use siamese method

i1 = (n+1)/2; j1 = i1+1; M = zeros(n); for k = 1:n^2 M(i1,j1) = k; i1 = i1 - 1; j1 = j1 +1; if i1 == 0 && j1 <= n i1 = n; elseif i1 > 0 && j1 > n j1 = 1; elseif i1 == 0 && j1 > n || M(i1,j1) > 0 j1 = rem(j1,n)+1; i1 = i1 + 1; end end

Walter Roberson
on 29 Sep 2011

length(unique([sum(M),sum(M,2)',sum(diag(M)),sum(flipud(M))]))==1

## 1 Comment

## Jan Simon (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/16948#comment_37520

@redcavalry: Please delete your former thread, which contains a Pascal version of the code.