magic

Magic square: equal row, column and diagonal sums.

Category: Mathematics > Elementary Math

Syntax

M = magic(n)

Returns an n-by-n matrix built from the integers 1 to n^2 whose rows, columns and both main diagonals add up to the same number.

Description

A different construction is used for odd orders, for orders divisible by 4, and for orders that are twice an odd number. The matrix returned is one particular magic square, not the only one of that size; for n = 2 no true magic square exists.

Magic squares are a convenient source of small test matrices of known sum, with integer entries and often nonzero determinant.

Input arguments

n
Nonnegative integer scalar. magic(0) is empty and magic(1) is 1.

Output arguments

M
The magic square, with common sum n*(n^2+1)/2.

Example

Checking the sums

M = magic(4)
sum(M)
sum(M, 2)'
trace(M)
sum(diag(fliplr(M)))
Output
M = 4×4

    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1
ans = 1×4

    34    34    34    34
ans = 1×4

    34    34    34    34
ans = 34
ans = 34

See also

hilb pascal hadamard gallery rosser