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

23 views (last 30 days)
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
  1 Comment
Paola
Paola on 28 Sep 2017
This is an example of my matrix (actually I have hundreds of columns and not just 4 as here).
1 2 3 4
4 5 6 8
7 8 9 8
2 3 7 4
5 7 2 9
3 5 1 7
1 0 0 1
I want to create a new matrix that contains only the columns whose last number is 1. The result would be this one:
1 4
4 8
7 8
2 4
5 9
3 7
1 1
To obtain this example I just selected manually the 2 columns to show, but, since I have a huge matrix and I can't write and check every single column...

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 28 Sep 2017
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)

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!