How to get log to = 1 or 0?
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
The function is basically to see if the arr is a magic square and output a true if it is and false if not. Also the use of the functions magic() and diag() are banned.
I have a function
function log = isMagicSquare(arr)
[M, N] = size(arr);
flip = fliplr(arr);
log = sum(arr) == sum(arr,2) == all(sum(arr(1:M+1:end))) == all(sum(flip(1:M+1:end)))
end
and I am trying to get it to = either 1 or 0 (logical) base on what is store in log.
These are the test code:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1147825/image.jpeg)
0 Commenti
Risposte (1)
John D'Errico
il 6 Ott 2022
First, I seriously want to suggest is it a BAD idea to use the variable named log in your code. Why? Because if not, then the next anxious question we see from you is to ask why the function log no longer works for you. This is because when you name a variable log, MATLAB will get confused as to which version of log it should be using, the function named log, or the variable named log?
For that matter, calling a variable log2 is also bad, as it too is a iuseful function in MATLAB. And don't forget log10. The point is, Think about the variable names you use.
What else? Oh, flip! Yes, flip is ALSO a useful function in MATLAB. Really, you need to be careful about these things, as soon you will be swearing at MATLAB, wondering why code that should work, now no longer works.
A square is magic if all of the rows sum to the same number, and the columns sum to that same number, as well as the two diagonals.
I'm not sure what you think should happen if the array is not square, since then the diagonal sums are meaningless. So at most I would return an error if M~=N.
Anyway, what would I do? How would I write the code? What if you just compute the sums of all of the rows. Append them to the sums of all of the columns. Then append the two diagonal sums. When you are done, you will have a vector of sums, of length (2*N+2). Are ALL of the elements in that vector the same? If not, then the square is not magic. Easy, peasy.
0 Commenti
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!