Main Content

magic

説明

M = magic(n) は、1 から n2 までの整数を使用して、行方向と列方向の和が等しくなる nn 列の行列を返します。次数 n は、有効な魔方陣を作成するためには 3 以上のスカラーでなければなりません。

すべて折りたたむ

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 である魔方陣行列のパターンを視覚的に調べます。パターンは、mod(n,4) の値が 0、2、または奇数のいずれであるかに応じて magic が 3 つの異なるアルゴリズムを使用していることを示します。

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)))) により使用可能な整数に変換します。

n3 より小さい場合、magic は魔方陣ではない行列、または縮退した魔方陣 1[] を返します。

データ型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char

拡張機能

バージョン履歴

R2006a より前に導入

参考

|