# Documentation

### This is machine translation

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

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

# magic

## Syntax

``M = magic(n)``

## Description

example

````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 ```

Use plots to visually examine the patterns present in magic square matrices.

Use `imagesc` to look at magic square matrices with orders between 9 and 24. The patterns displayed point to the three different algorithms used, depending on whether `n` is odd, even, or divisible by 4.

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

## Input Arguments

collapse all

Matrix order, specified as a scalar integer greater than or equal to 3. If `n` is complex, not an integer, or not scalar, then `magic` converts it into a usable integer with `floor(real(double(n(1))))`.

If you supply `n` less than `3`, then `magic` 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`

## 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 4

• `n` divisible by 4

For example, 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```.

```table((3:20)',r(3:20)','VariableNames',{'Order','Rank'}) ans = 18×2 table Order Rank _____ ____ 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 ```

## See Also

#### Introduced before R2006a

Was this topic helpful?

#### The Manager's Guide to Solving the Big Data Conundrum

Download white paper