| MATLAB Function Reference | Search  Help Desk |
| magic | Examples See Also |
Syntax
M=magic(n)
Description
M = magic(n)
returns an n-by-n matrix constructed from the integers 1 through n^2 with equal row and column sums. The order n must be a scalar greater than or equal to 3.
Remarks
A magic square, scaled by its magic sum, is doubly stochastic.Examples
The magic square of order 3 isMThis is called a magic square because the sum of the elements in each column is the same.=magic(3) M = 8 1 6 3 5 7492
And the sum of the elements in each row, obtained by transposing twice, is the same.sum(M)=151515
This is also a special magic square because the diagonal elements have the same sum.sum(M')'=151515
sum(diag(M)) =
15
The value of the characteristic sum for a magic square of order n is
sum(1:n^2)/nwhich, when
n = 3, is 15.
Algorithm
There are three different algorithms:n
n not divisible by four
n divisible by four.
forn=3:20A=magic(n);plot(A,'-');r(n)=rank(A); end r
Limitations
If you supplyn less than 3, magic returns either a nonmagic square, or else the degenerate magic squares 1 and [].
See Also
ones, rand