gpt4 book ai didi

matrix - 填充这个矩阵的简单方法?

转载 作者:行者123 更新时间:2023-12-04 09:01:38 25 4
gpt4 key购买 nike

我想填充一个 n * n (n 为奇数) 矩阵如下:

_   _   _   23  22  21  20
_ _ 24 10 9 8 37
_ 25 11 3 2 19 36
26 12 4 1 7 18 35
27 13 5 6 17 34 _
28 14 15 16 33 _ _
29 30 31 32 _ _ _

使用 Mathematica 执行此操作的简单方法是什么?

最佳答案

使用这个辅助函数:

Clear[makeSteps];
makeSteps[0] = {};
makeSteps[m_Integer?Positive] :=
Most@Flatten[
Table[#, {m}] & /@ {{-1, 0}, {-1, 1}, {0, 1}, {1, 0}, {1, -1}, {0, -1}}, 1];

我们可以构造矩阵为
constructMatrix[n_Integer?OddQ] :=
Module[{cycles, positions},
cycles = (n+1)/2;
positions =
Flatten[FoldList[Plus, cycles + {#, -#}, makeSteps[#]] & /@
Range[0, cycles - 1], 1];
SparseArray[Reverse[positions, {2}] -> Range[Length[positions]]]];

要获得您描述的矩阵,请使用
constructMatrix[7] // MatrixForm

这背后的想法是检查连续数字 1.. 的位置遵循的模式。你可以看到这些形成了循环。第零个循环是微不足道的 - 在位置 {0,0} 处包含一个数字 1 (如果我们从中心计算位置)。下一个循环是通过在位置 {1,-1} 处取第一个数字 (2) 来形成的。并一一添加以下步骤: {0, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 0} (当我们围绕中心移动时)。第二个周期类似,但我们要从 {2,-2}开始,将前面的每一步重复两次,并添加第六步(向上),只重复一次: {0, -1} .第三个循环类似:从 {3,-3} 开始, 重复所有步骤 3 次,除了 {0,-1}只重复两次。辅助功能 makeSteps使过程自动化。然后在主函数中,我们必须将所有位置收集在一起,然后添加到它们 {cycles, cycles}因为它们是从中心开始计算的,中心位置是 {cycles,cycles} .最后,我们构造了 SparseArray在这些职位之外。

关于matrix - 填充这个矩阵的简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8209264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com