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

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

    I think I'd do it the same way, but here are some other ways of doing it:

    -With MapIndexed

    newa = MapIndexed[Insert[#1, column[[#2[[1]]]], 2] &, a]
    

    -With Sequence:

    newa = a;
    newa[[All, 1]] = Transpose[{newa[[All, 1]], column}];
    newa = Replace[a, List -> Sequence, {3}, Heads -> True]
    

    Interestingly, this would seem to be a method that works 'in place', i.e. it wouldn't really require a matrix copy as stated in Leonid's answer and if you print the resulting matrix it apparently works as a charm.

    However, there's a big catch. See the problems with Sequence in the mathgroup discussion "part assigned sequence behavior puzzling".

提交回复
热议问题