How to extract matrix value given condition on another column

1 回表示 (過去 30 日間)
Jesutoyosi Awoyeye
Jesutoyosi Awoyeye 2017 年 9 月 5 日
編集済み: Jesutoyosi Awoyeye 2017 年 9 月 5 日
So i have a matrix: [1 2 3 4; 5 6 7 8; 1 0 1 1]
The condition is that the third column must equal one. Then I take that corresponding row to extract the value from column 2.
So i need a code that extracts 5, 7, and 8 into a separate matrix.

回答 (1 件)

Cam Salzberger
Cam Salzberger 2017 年 9 月 5 日
Hello Jesutoyosi,
Based on your example matrix, I believe you meant that you want to extract from row 2 every value that is a 1 in row 3.
In that case, logical indexing is your best friend.
whichCols = oldMat(3,:) == 1;
newMat = oldMat(2,whichCols);
Or, because 1 is able to be converted to true, and 0 to false, you can just do this:
newMat = oldMat(2, logical(oldMat(3,:)));
-Cam
  1 件のコメント
Jesutoyosi Awoyeye
Jesutoyosi Awoyeye 2017 年 9 月 5 日
編集済み: Jesutoyosi Awoyeye 2017 年 9 月 5 日
Will this same code apply to all dimensions? The dimension of the matrix that I am dealing with is 195x6. I am extracting values from column 4 given that the values in column 6 is 1.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by