在Mathematica中通过循环将元素插入矩阵

时间:2014-05-07 12:26:15

标签: for-loop matrix resize wolfram-mathematica

我试图通过for循环增加下面矩阵的大小但是代码给出了一个错误,直到这一点我还没有找到解决方案。这是我的代码,

m = 1;
n = 1;
mat2 = Table[0, {m}, {n}];
For[i = 1, i <= n + 1, i++,
    For[j = 1, j <= m + 1, j++,
            mat2[[i, j]] = j
    ];
  ];
mat2 // MatrixForm

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

In[1]:= m = 2; n = 2; mat2 = Table[i + j, {i, m}, {j, n}];
mat2 = ArrayPad[mat2, {0, 1}];
mat2 // MatrixForm

Out[3]//MatrixForm=
{{2, 3, 0},
 {3, 4, 0},
 {0, 0, 0}}

答案 1 :(得分:0)

使用SparseArray ..

的一个巧妙的小技巧
 mat = SparseArray[Table[1, {5}, {5}]] 

enter image description here

 mat = SparseArray[Prepend[ArrayRules[mat], {6, 8} -> 9]]

请注意,这会将整个数组复制到一个新的更大的数组(就像ArrayPad一样),所以你真的不想经常为大数组做这件事。

enter image description here

同样是&#34;任务&#34;进入现有职位有效,但出于性能原因,你不想这样做:

 mat = SparseArray[Prepend[ArrayRules[mat], {2, 2} -> 3]]

enter image description here

而不是增长数组,你最好先定义一个足够大的SparseArray(创建一个巨大的空SparseArray几乎没有内存命中)

 mat = SparseArray[Table[1, {5}, {5}], {1000, 1000}];
 mat[[6, 8]] = 9;
 mat[[2, 2]] = 3;

(只是不要尝试打印这个..)

完成后保存非空部分:

 mat=SparseArray[ArrayRules[mat]]

enter image description here