Main Content

magic

마방진(Magic Square)

설명

예제

M = magic(n)은 행과 열의 합계가 동일하고 1 ~ n2 범위의 정수로 생성된 n×n 행렬을 반환합니다. 유효한 마방진을 만들려면 차수 n3보다 크거나 같은 스칼라여야 합니다.

예제

모두 축소

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))))과 함께 사용할 수 있는 정수로 변환합니다.

n3보다 작게 지정하면 magic은 마방진이 아닌 정사각 행렬이나, 퇴화된(Degenerate) 마방진인 1[]을 반환합니다.

데이터형: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char

확장 기능

버전 내역

R2006a 이전에 개발됨

참고 항목

|