Compute the third-order magic square
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.
ans = 1×3 15 15 15
ans = 3×1 15 15 15
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
n— Matrix order
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
If you supply
n less than
magic returns either a nonmagic square, or the
degenerate magic squares
Usage notes and limitations:
See Variable-Sizing Restrictions for Code Generation of Toolbox Functions (MATLAB Coder).
backgroundPoolor accelerate code with Parallel Computing Toolbox™
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.