magic
Magic square
Syntax
Description
Examples
Third-Order Magic Square
Compute the third-order magic square M
.
M = magic(3)
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.
sum(M)
ans = 1×3
15 15 15
sum(M,2)
ans = 3×1
15
15
15
Magic Square Visualization
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
Input Arguments
n
— Matrix order
scalar integer
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
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
See Variable-Sizing Restrictions for Code Generation of Toolbox Functions (MATLAB Coder).
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool
or accelerate code with Parallel Computing Toolbox™ ThreadPool
.
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
Version History
Introduced before R2006a
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)