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

前端 未结 5 1400
旧时难觅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:05

    I originally posted this as a comment (now deleted)

    Based on a method given by user656058 in this question (Mathematica 'Append To' Function Problem) and the reply of Mr Wizard, the following alternative method of adding a column to a matrix, using Table and Insert, may be gleaned:

    (a = {{1, 2, 3}, {4, 0, 8}, {7, 8, 0}});
    column = {97, 98, 99};
    
    Table[Insert[a[[i]], column[[i]], 2], {i, 3}] // MatrixForm
    

    giving

    enter image description here

    Similarly, to add a column of zeros (say):

    Table[Insert[#[[i]], 0, 2], {i, Dimensions[#][[1]]}] & @ a 
    

    As noted in the comments above, Janus has drawn attention to the 'trick' of adding a column of zeros by the ArrayFlatten method (see here)

    ArrayFlatten[{{Take[#, All, 1], 0, Take[#, All, -2]}}] & @ 
      a // MatrixForm
    

    Edit

    Perhaps simpler, at least for smaller matrices

    (Insert[a[[#]], column[[#]], 2] & /@ Range[3]) // MatrixForm
    

    or, to insert a column of zeros

    Insert[a[[#]], 0, 2] & /@ Range[3]
    

    Or, a little more generally:

    Flatten@Insert[a[[#]], {0, 0}, 2] & /@ Range[3] // MatrixForm
    

    May also easily be adapted to work with Append and Prepend, of course.

提交回复
热议问题