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

조회 수: 8 (최근 30일)
Paola
Paola 2017년 9월 28일
댓글: Paola 2017년 9월 28일
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
Paola
Paola 2017년 9월 28일
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...

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2017년 9월 28일
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)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by