magic - Magic square - MATLAB (original) (raw)

Main Content

Syntax

Description

M = magic([n](#d126e1032165)) returns ann-by-n matrix constructed from the integers 1 throughn2 with equal row and column sums. The order n must be a scalar greater than or equal to3 in order to create a valid magic square.

example

Examples

collapse all

Compute the third-order magic square M.

M = 3×3

 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.

Visually examine the patterns in magic square matrices with orders between 9 and 24 using imagesc. The patterns show that magic uses three different algorithms, depending on whether the value of mod(n,4) is 0, 2, or odd.

for n = 1:16 subplot(4,4,n) ord = n+8; m = magic(ord); imagesc(m) title(num2str(ord)) axis equal axis off end

Figure contains 16 axes objects. Hidden axes object 1 with title 9 contains an object of type image. Hidden axes object 2 with title 10 contains an object of type image. Hidden axes object 3 with title 11 contains an object of type image. Hidden axes object 4 with title 12 contains an object of type image. Hidden axes object 5 with title 13 contains an object of type image. Hidden axes object 6 with title 14 contains an object of type image. Hidden axes object 7 with title 15 contains an object of type image. Hidden axes object 8 with title 16 contains an object of type image. Hidden axes object 9 with title 17 contains an object of type image. Hidden axes object 10 with title 18 contains an object of type image. Hidden axes object 11 with title 19 contains an object of type image. Hidden axes object 12 with title 20 contains an object of type image. Hidden axes object 13 with title 21 contains an object of type image. Hidden axes object 14 with title 22 contains an object of type image. Hidden axes object 15 with title 23 contains an object of type image. Hidden axes object 16 with title 24 contains an object of type image.

Input Arguments

collapse all

Matrix order, specified as a scalar integer greater than or equal to 3. Ifn is complex, not an integer, or not scalar, thenmagic converts it into a usable integer withfloor(real(double(n(1)))).

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

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char

Extended Capabilities

expand all

Usage notes and limitations:

Version History

Introduced before R2006a