如何在矩阵中插入一列,正确的 Mathematica 方式 [英] How to insert a column into a matrix, the correct Mathematica way
问题描述
我认为 Mathematica 偏向于行而不是列.
I think Mathematica is biased towards rows not columns.
给定一个矩阵,插入一行似乎很容易,只需使用Insert[]
Given a matrix, to insert a row seems to be easy, just use Insert[]
(a = {{1, 2, 3}, {4, 0, 8}, {7 , 8, 0}}) // MatrixForm
1 2 3
4 0 8
7 8 0
row = {97, 98, 99};
(newa = Insert[a, row, 2]) // MatrixForm
1 2 3
97 98 99
4 0 8
7 8 0
但是要插入一列,经过一番折腾,我找到了2种方法,我在下面展示,想请教这里的高手他们是否看到了更短更直接的方法(Mathematica有这么多命令,我可以有忽略了一个以非常直接的方式做这种事情的方法),因为我认为我现在拥有的方法对于这样一个基本操作来说仍然太复杂了.
But to insert a column, after some struggle, I found 2 ways, I show below, and would like to ask the experts here if they see a shorter and more direct way (Mathematica has so many commands, and I could have overlooked one that does this sort of thing in much direct way), as I think the methods I have now are still too complex for such a basic operation.
必须做双转置:
a = {{1, 2, 3}, {4, 0, 8}, {7 , 8, 0}}
column = {97, 98, 99}
newa = Transpose[Insert[Transpose[a], column, 2]]
1 97 2 3
4 98 0 8
7 99 8 0
第二种方法
使用 SparseArray,但需要注意索引位置.这样做有点尴尬:
Second method
Use SparseArray, but need to watch out for index locations. Kinda awkward for doing this:
(SparseArray[{{i_, j_} :> column[[i]] /; j == 2, {i_, j_} :> a[[i, j]] /; j == 1,
{i_, j_} :> a[[i, j - 1]] /; j > 1}, {3, 4}]) // Normal
1 97 2 3
4 98 0 8
7 99 8 0
问题是:有没有更实用的方式,比上面的短一点?我当然可以使用上面的一个,并用一个函数包装整个东西,比如 insertColumn[...]
以使其易于使用.但想看看是否有比我现有的方法更简单的方法.
The question is: Is there a more functional way, that is little shorter than the above? I could ofcourse use one of the above, and wrap the whole thing with a function, say insertColumn[...]
to make it easy to use. But wanted to see if there is an easier way to do this than what I have.
作为参考,这就是我在 Matlab 中的做法:
For reference, this is how I do this in Matlab:
EDU>> A=[1 2 3;4 0 8;7 8 0]
A =
1 2 3
4 0 8
7 8 0
EDU>> column=[97 98 99]';
EDU>> B=[A(:,1) column A(:,2:end)]
B =
1 97 2 3
4 98 0 8
7 99 8 0
推荐答案
你的双 Transpose
方法看起来不错.对于非常大的矩阵,这将快 2-3 倍:
Your double Transpose
method seems fine. For very large matrices, this will be 2-3 times faster:
MapThread[Insert, {a, column, Table[2, {Length[column]}]}]
如果你想模仿你的 Matlab 方式,最接近的可能是这个:
If you want to mimic your Matlab way, the closest is probably this:
ArrayFlatten[{{a[[All, ;; 1]], Transpose[{column}], a[[All, 2 ;;]]}}]
请记住,插入需要制作矩阵的完整副本.因此,如果您打算以这种方式构建矩阵,那么预先分配矩阵(如果您知道其大小)并通过 Part
进行就地修改会更有效.
Keep in mind that insertions require making an entire copy of the matrix. So, if you plan to build a matrix this way, it is more efficient to preallocate the matrix (if you know its size) and do in-place modifications through Part
instead.
这篇关于如何在矩阵中插入一列,正确的 Mathematica 方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!