MATLAB: How to select specific columns in a matrix and create a new one

create new matrixmatrixselect columnsselect rows

Hello, I am very new to Matlab, so my question could be too elementary… I have a huge matrix made of 7 rows. In the last row, there are only 1 or 0. I need to create a new matrix from the original one, taking only the columns which last row value is 1. Or, in other terms, I want to discard all those columns whose last value is 0. Is there a simple way to do it?
Thank you

Best Answer

Either
newmatrix = yourmatrix(:, yourmatrix(end, :) == 1)
Or
newmatrix = yourmatrix(:, logical(yourmatrix(end, :)))
will do it.
This is very basic indexing so you should go through the Getting Started Tutorial. What the above does is:
  • get a logical row vector of which columns are 1 and which are 0, using either yourmatrix(end, :) == 1 or logical(yourmatrix(end, :)),
  • then use that logical vector of 0 and 1 to filter the column with yourmatrix(:, logicalvector)