How to insert a column into a matrix, the correct Mathematica way

前端 未结 5 1399
旧时难觅i
旧时难觅i 2021-01-30 14:40

I think Mathematica is biased towards rows not columns.

Given a matrix, to insert a row seems to be easy, just use Insert[]

(a = {{1, 2, 3},         


        
5条回答
  •  孤独总比滥情好
    2021-01-30 15:02

    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]}]}]
    

    If you want to mimic your Matlab way, the closest is probably this:

    ArrayFlatten[{{a[[All, ;; 1]], Transpose[{column}], a[[All, 2 ;;]]}}]
    

    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.

提交回复
热议问题