Remove a column from a matrix in GNU Octave

Eric Leschinski picture Eric Leschinski · Sep 12, 2012 · Viewed 38.5k times · Source

In GNU Octave, I want to be able to remove specific columns from a matrix. In the interest of generality. I also want to be able to remove specific rows from a matrix.

Suppose I have this:

mymatrix = eye(5)

mymatrix =

Diagonal Matrix

   1   0   0   0   0
   0   1   0   0   0
   0   0   1   0   0
   0   0   0   1   0
   0   0   0   0   1

I want to remove columns 2 and 4, but when I remove column 2, the position of column 4 has moved to column 3, and that makes my head hurt. There has to be a better way!

Answer

pors picture pors · Nov 12, 2014

In case you don't know the exact number of columns or rows you can use the magic "end" index, e.g.:

mymatrix(:,2:end)  % all but first column

mymatrix(2:end,:)  % all but first row

This also allows you to slice rows or columns out of a matrix without having to reassign it to a new variable.