Main Content

本页翻译不是最新的。点击此处可查看最新英文版本。

magic

幻方矩阵

说明

示例

M = magic(n) 返回由 1n2 的整数构成并且总行数和总列数相等的 n×n 矩阵。n 的阶数必须是大于或等于 3 的标量才能创建有效的幻方矩阵。

示例

全部折叠

计算三阶幻方矩阵 M

M = magic(3)
M = 3×3

     8     1     6
     3     5     7
     4     9     2

每列中元素的总和等于每行中元素的总和。

sum(M)
ans = 1×3

    15    15    15

sum(M,2)
ans = 3×1

    15
    15
    15

使用 imagesc 观察 9 阶到 24 阶幻方矩阵的图案。这些图案表明 magic 使用三种不同的算法,取决于 mod(n,4) 的值是 0、2 还是奇数。

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. Axes object 1 with title 9 contains an object of type image. Axes object 2 with title 10 contains an object of type image. Axes object 3 with title 11 contains an object of type image. Axes object 4 with title 12 contains an object of type image. Axes object 5 with title 13 contains an object of type image. Axes object 6 with title 14 contains an object of type image. Axes object 7 with title 15 contains an object of type image. Axes object 8 with title 16 contains an object of type image. Axes object 9 with title 17 contains an object of type image. Axes object 10 with title 18 contains an object of type image. Axes object 11 with title 19 contains an object of type image. Axes object 12 with title 20 contains an object of type image. Axes object 13 with title 21 contains an object of type image. Axes object 14 with title 22 contains an object of type image. Axes object 15 with title 23 contains an object of type image. Axes object 16 with title 24 contains an object of type image.

输入参数

全部折叠

矩阵的阶次,指定为大于或等于 3 的整数标量。如果 n 是复数,不是整数,也不是标量,则 magic 会使用 floor(real(double(n(1)))) 将其转换为可使用的整数。

如果您提供的 n 小于 3,则 magic 将返回非幻方矩阵或退化幻方矩阵 1[]

数据类型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char

扩展功能

版本历史记录

在 R2006a 之前推出

另请参阅

|