Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to insert a column into a matrix, the correct Mathematica way
    primarykey
    data
    text
    <p>I think Mathematica is biased towards rows not columns.</p> <p>Given a matrix, to insert a row seems to be easy, just use <code>Insert[]</code></p> <pre><code>(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 </code></pre> <p>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.</p> <h2>First method</h2> <p>Have to do double transpose:</p> <pre><code>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 </code></pre> <h2>Second method</h2> <p>Use SparseArray, but need to watch out for index locations. Kinda awkward for doing this:</p> <pre><code>(SparseArray[{{i_, j_} :&gt; column[[i]] /; j == 2, {i_, j_} :&gt; a[[i, j]] /; j == 1, {i_, j_} :&gt; a[[i, j - 1]] /; j &gt; 1}, {3, 4}]) // Normal 1 97 2 3 4 98 0 8 7 99 8 0 </code></pre> <p>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 <code>insertColumn[...]</code> to make it easy to use. But wanted to see if there is an easier way to do this than what I have.</p> <p>For reference, this is how I do this in Matlab:</p> <pre><code>EDU&gt;&gt; A=[1 2 3;4 0 8;7 8 0] A = 1 2 3 4 0 8 7 8 0 EDU&gt;&gt; column=[97 98 99]'; EDU&gt;&gt; B=[A(:,1) column A(:,2:end)] B = 1 97 2 3 4 98 0 8 7 99 8 0 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload