How can i check if a matrix is magic square or not?

조회 수: 34 (최근 30일)
maha sh
maha sh 2017년 11월 24일
댓글: Stephen23 2023년 6월 22일
I have to Develop a Matlab script to determine if the numbers stored in a square integer matrix form a magic square or not, without using loops !!

채택된 답변

Jan
Jan 2017년 11월 27일
편집: Jan 2017년 11월 27일
if(s1==s2==s3==s4)
This is processed from left to right:
s1==s2
This is either TRUE (1) or FALSE (0). In the next step you compare:
0==s3 or 1==s3
and the same in the last step:
0==s4 or 1==s4
You want:
if isequal(s1, s2, s3, s4)
or
if s1==s2 && s2==s3 && s3==s4
Do you see how easy suggesting a solution is, when you post the relevant part of the code?
  댓글 수: 3
Maahir Bharadia
Maahir Bharadia 2019년 3월 4일
what exactly does s1==s2 mean?
does it necesarrily mean that all rows and columns sum to the same number?
Or does it mean that all corresponding rows and columns are equal?
Walter Roberson
Walter Roberson 2019년 3월 4일
In the way that the user generated those values, s1 and s2 are vectors of the same length but different orientations, and s3 and s4 were scalars.
In R2016b or later, if you use s1 == s2 when s1 and s2 are vectors of different orientation, then the effect is the same as bsxfun(@equal, s1, s2) which produces a rectangular matrix of logical values, comparing each value against each other value. You could do that, but it is not efficient.

댓글을 달려면 로그인하십시오.

추가 답변 (4개)

Guillaume
Guillaume 2017년 11월 24일
편집: Guillaume 2017년 11월 24일
Refer to the definition of a magic square and test for that, i.e. sum the rows, columns and diagonal and see if they're all equal. I don't understand what difficulty there is.
  댓글 수: 4
maha sh
maha sh 2017년 11월 27일
편집: maha sh 2017년 11월 27일
@Jan Simon
M = magic(3)
s1=sum(M)
s2=sum(M,2)
s3=sum(diag(M))
s4=sum(diag(flipud(M))) % or s4=sum(diag(flip(M)))
I wanna check using if else statement if s1,s2,s3 and s4 are equal I trayed to use
if(s1==s2==s3==s4)
disp('somthing ');
else
disp (' something else '); end
they told me that using if (s1==s2==s3==s4) is wrong, so the whole problem is how to compare them to check if they're equal or not + i can't use loops
Jan
Jan 2017년 11월 27일
See my answer.

댓글을 달려면 로그인하십시오.


Image Analyst
Image Analyst 2017년 11월 24일
Is this homework? Sounds like homework. If it is, add the tag "homework" and read this link
Hints:
Get the size with size() and make sure that there are only two dimensions (e.g. it's not a 3-D or 4-D matrix) and the length of each of those dimensions are equal (i.e., it's square).
If it's square then create a magic square with magic(rows).
Use isequal() to compare your matrix to the "official" one. You also have to use the transpose operator and the flipud() and fliplr() functions to test if any rotation or mirror image is equal. If any of those orientations is equal, then it's a magic square.
The other approach is to call sum(m,1) and sum(m,2) and then see if all values are the same, like with the all() or diff() function - lot of ways to do this. Then use eye() to sum the diagonals. You'll need to use fliplr() to get the diagonal from upper right to lower left.
  댓글 수: 4
Stephen23
Stephen23 2017년 11월 25일
편집: Stephen23 2017년 11월 25일
"I said to do rotations and flips"
Totally irrelevant. The translations and reflections are not the reason why this concept is flawed. Simply put:
  • MATLAB only generates one magic square for any size (using a deterministic algorithm).
  • There are many possible magic squares for each size >= 4x4 (disregarding translations and reflections).
  • Your concept therefore only checks for one of those possible magic squares: the one that MATLAB happens to generate.
  • Hence your concept incorrectly identifies all of the other magic squares as not being magic.
Lets demonstrate with a simple random 4x4 magic square (NOT from MATLAB):
>> M = [2,8,11,13;10,16,5,3;15,9,4,6;7,1,14,12]
M =
2 8 11 13
10 16 5 3
15 9 4 6
7 1 14 12
>> magic(4) % compare to MATLAB
ans =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Are they the same? A simple check by eye will confirm that these are not translations or reflections of each other. Ditto for another 878 different 4x4 magic squares which your concept incorrectly identifies as not being magic. Your concept will correctly identify just one of those 880 4x4 magic squares as being magic: the one the MATLAB happens to generate.
The task requests to "determine if the numbers stored in a square integer matrix form a magic square or not". Your concept incorrectly identifies almost every magic square that exists as being non-magic (except for the small subset that MATLAB can generate). Therefore it does not fulfill the requirements of the task, because it will incorrectly identify almost 100% of all magic squares as not being magic: your concept will correctly identify just one of the estimated 1.8e19 6x6 magic squares, and is thus quite close to 0% correct.
Simple summary: the concept does not work because there are many magic squares for any size >= 4x4. Translations and reflections are totally irrelevant to this issue.
Image Analyst
Image Analyst 2017년 11월 25일
Thank you - I understand now.

댓글을 달려면 로그인하십시오.


Jos (10584)
Jos (10584) 2017년 11월 24일
You can also take a look at chapter 10, titled "Magic Squares", of the book Experiments with Matlab, by Cleve Moler: https://uk.mathworks.com/moler/exm.html
Very informative reading regarding this question :)

Thomas
Thomas 2023년 6월 21일
try:
function ismagic = ismagic(M)
%ISMAGIC checks if a matrix M is a magic square or not
if size(M,1) ~= size(M,2)
ismagic = false;
return;
else
Msums = [sum(M,1)'; sum(M,2); sum(diag(M)); sum(diag(flip(M)))]; % create an array containing all 2*n + 2 sums to be checked
if max(Msums) ~= min(Msums)
ismagic = false;
else
ismagic = true;
end
return;
end
end
  댓글 수: 1
Stephen23
Stephen23 2023년 6월 22일
The basic concept is nice. A few tips:
  • best not to confuse things using the same output variable name as the function itself.
  • RETURN is not required (MATLAB functions return at the end).
  • instead of IF ELSE just allocate the logical directly as the output.
function X = ismagic(M)
% ISMAGIC checks if a matrix M is a magic square or not
X = false;
if isequal(diff(size(M)),0) % ISMATRIX
V = [sum(M,1).';sum(M,2);sum(diag(M));sum(diag(flip(M)))];
X = max(V)==min(V);
end
end

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by