【问题标题】:Spiral Matrix Procedure in MapleMaple 中的螺旋矩阵程序
【发布时间】:2014-09-16 15:18:05
【问题描述】:

我想写一个程序来获取一个方阵并让它输出一个螺旋矩阵。

例如;

M:=Matrix(3,[[1,2,3],[4,5,6],[7,8,9]]);

会变成

S:=Matrix(3,[[1,2,3],[8,9,4],[7,6,5]]);

从左上角开始,每一行顺时针顺时针一直到中间。

我的第一个想法是我需要能够从矩阵中调用每个元素 (m_i,j) 并告诉它去哪里。我可以为每个方阵编写一个不同的过程,指定矩阵中的每个元素应该移动到的位置。因为我无法让它为 n 工作。

这是一个 3x3 矩阵的内容

 Spiral := proc(a1,a2,a3,b1,b2,b3,c1,c2,c3)
 local M,S;
 M:=Matrix(3,[[a1,a2,a3],[b1,b2,b3],[c1,c2,c3]]);
 S:=Matrix(3,[[a1,a2,a3],[c2,c3,b1],[c1,b3,b2]]);
 print(M);
 print(S);
 end:

 Spiral(1,2,3,4,5,6,7,8,9);

我很难在 Maple 中找到有关矩阵的信息。任何有关使用 Maple 的提示将不胜感激。谢谢。

【问题讨论】:

  • 您确定要 S:=Matrix(3,[[1,2,3],[8,9,4],[7,6,5 ]]);而不是:S:=Matrix(3,[[1,2,3],[9,8,4],[7,6,5]]); ?
  • 是的,我希望最后一个数字成为中心。所以 m_3,3 -> m_2,2。对于 3x3 矩阵,即。

标签: matrix maple


【解决方案1】:

我认为这个问题没有特别紧凑的解决方案。这是我想出的解决方案。它接受一个方阵作为输入,并返回另一个矩阵,它是输入矩阵的螺旋。

spiral:=proc(M::Matrix)
    local size, spiralCount, currentRow, currentCol, MIndex, k;
    local spiralMatrix;

    size := numelems(M[1]);
    spiralCount := size;
    currentRow := 1;
    currentCol := 0;
    MIndex := 0;
    spiralMatrix := Matrix(size, size);

    while spiralCount > 0 do
    for k from 1 to spiralCount do
        currentCol:=currentCol + 1;
        spiralMatrix[currentRow,currentCol] := M[iquo(MIndex,size) + 1,(MIndex mod size) + 1];
        MIndex := MIndex + 1;
    end do:
    for k from 1 to spiralCount-1 do
        currentRow:=currentRow + 1;
        spiralMatrix[currentRow,currentCol] := M[iquo(MIndex,size) + 1,(MIndex mod size) + 1];
        MIndex := MIndex + 1;
    end do:
    for k from 1 to spiralCount-1 do
        currentCol:=currentCol - 1;
        spiralMatrix[currentRow,currentCol] := M[iquo(MIndex,size) + 1,(MIndex mod size) + 1];
        MIndex := MIndex + 1;
    end do:
    for k from 1 to spiralCount-2 do
        currentRow:=currentRow - 1;
        spiralMatrix[currentRow,currentCol] := M[iquo(MIndex,size) + 1,(MIndex mod size) + 1];
        MIndex := MIndex + 1;
    end do:
    spiralCount := spiralCount - 2;
    end do:


    return spiralMatrix;
end proc:


> m:=Matrix([[1,2,3],[4,5,6],[7,8,9]]);
                               [1    2    3]
                               [           ]
                          m := [4    5    6]
                               [           ]
                               [7    8    9]
> spiral(m);       
                             [1    2    3]
                             [           ]
                             [8    9    4]
                             [           ]
                             [7    6    5]

请随时问我有关此实现和/或有关如何使用 Matrix 类型的任何问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多