MATLAB Function Reference
  Go to function:
    Search    Help Desk 
magic    Examples   See Also

Magic square

Syntax

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 is

This is called a magic square because the sum of the elements in each column is the same.

And the sum of the elements in each row, obtained by transposing twice, is the same.

This is also a special magic square because the diagonal elements have the same sum.

The value of the characteristic sum for a magic square of order n is

which, when n = 3, is 15.

Algorithm

There are three different algorithms: one for odd n, one for even n not divisible by four, and one for even n divisible by four.

To make this apparent, type:

Limitations

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

See Also

ones        Create an array of all ones

rand        Uniformly distributed random numbers and arrays



[ Previous | Help Desk | Next ]