Back to Core Functions

magic

Magic square

Syntax

M = magic(n)

Description

Creates an n×n magic square matrix where the sum of each row, column, and both main diagonals equals the same magic constant: n(n²+1)/2. For n=1 returns [1], for n=2 there is no magic square so returns [1 3; 4 2] (not a true magic square). Works for all n ≥ 1.

Parameters

NameDescription
nSize of the magic square (n ≥ 1)

Returns

n×n magic square NDArray

Examples

Try It
>> magic(3)
8  1  6
3  5  7
4  9  2
Try It
>> magic(4)
16  2  3  13
 5  11  10  8
 9  7  6  12
 4  14  15  1
Try It
>> sum(magic(5))
65  65  65  65  65

See Also