is this code correct?

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

1 个评论

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

请先登录,再进行评论。

回答(4 个)

the cyclist
the cyclist 2011-9-28

0 个投票

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.
you might want to try
type magic
TMW do it in 4 lines.

2 个评论

Guessing that TMW doesn't use the "terrace method", but have to admit that I don't know for sure.
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.)

请先登录,再进行评论。

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
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

3 个评论

length(unique([sum(M),sum(M,2)',sum(diag(M)),sum(flipud(M))]))==1
I think to be a magic square the sorted elements have to equal 1:M
Yes, Daniel. Added.

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Repeated Measures and MANOVA 的更多信息

标签

提问:

2011-9-28

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by