Documentation

This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.

我们为许可用户提供了部分翻译好的中文文档。您只需登录便可查阅这些文档

magic

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.

Examples

collapse all

Compute the third-order magic square, M.

M = magic(3)
M =

     8     1     6
     3     5     7
     4     9     2

The sum of the elements in each column and the sum of the elements in each row are the same.

sum(M)
ans =

    15    15    15

sum(M,2)
ans =

    15
    15
    15

Limitations

If you supply n less than 3, magic returns either a nonmagic square, or else the degenerate magic squares 1 and [].

More About

collapse all

Tips

A magic square, scaled by its magic sum, is doubly stochastic.

Algorithms

There are three different algorithms:

  • n odd

  • n even but not divisible by four

  • n divisible by four

To make this apparent, type

for n = 3:20
    A = magic(n);
    r(n) = rank(A);
end

For n odd, the rank of the magic square is n. For n divisible by 4, the rank is 3. For n even but not divisible by 4, the rank is n/2 + 2.

[(3:20)',r(3:20)']
ans =
     3     3
     4     3
     5     5
     6     5
     7     7
     8     3
     9     9
    10     7
    11    11
    12     3
    13    13
    14     9
    15    15
    16     3
    17    17
    18    11
    19    19
    20     3

Plotting A for n = 18, 19, 20 shows the characteristic plot for each category.

See Also

|

Introduced before R2006a


Was this topic helpful?