Using a binary matrix as an index to select values from another matrix

Hi all,
I think this is a really beginner question, but I can't seem to find the relevant answers online.
If I have the following matrix:
% 3x2
index_matrix = [0,0;1,0;1,1;]
% 3x2
p = [13,12;11,19;22,23;]
I wish to select the corresponding value in p if the value at the same position in index_matrix = 1.
If the value in index_matrix is 0, then the corresponding value should be set to 0.
That is, I wish to have the following:
result = [0,0;11,0;22,23;]
Thank you in advance!

 採用された回答

Kai Franke
Kai Franke 2019 年 6 月 14 日
result = p.*index_matrix
matrix multiplication is the keyword hehe
Best regards.

3 件のコメント

Stephen23
Stephen23 2019 年 6 月 14 日
編集済み: Stephen23 2019 年 6 月 14 日
"matrix multiplication is the keyword hehe"
Actually the keyword is element-wise multiplication (that is what you used in your answer).
Matrix multiplcation is something quite different, as the MATLAB documentation explains:
Shuyi Jia
Shuyi Jia 2019 年 6 月 14 日
編集済み: Shuyi Jia 2019 年 6 月 14 日
Thanks! That works!
Just a follow-up question, what if my index_matrix is like this:
index_matrix = [1,0;3.5,1;0,6;]
p = [13,12;11,19;22,23;]
And I still wish to obtain the corresponding values in p, only if the values at the same positions in index_matrix == 1 (not 3.5 or 6; 0 for all other values)?
That is:
result = [13,0;0,19;0,0;]
Kai Franke
Kai Franke 2019 年 6 月 14 日
@Stephen Cobeldick
oh yeah you are absolutely right! Element-wise multiplication. My answer was very sloppy, my bad. Thanks for the correction!

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

その他の回答 (1 件)

Stephen23
Stephen23 2019 年 6 月 14 日
>> X = [1,0;3.5,1;0,6];
>> p = [13,12;11,19;22,23];
>> p.*(X==1)
ans =
13 0
0 19
0 0

1 件のコメント

Shuyi Jia
Shuyi Jia 2019 年 6 月 14 日
編集済み: Shuyi Jia 2019 年 6 月 14 日
Thank you! I didn't know one can manipulate matrix like this. New to matlab!

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

カテゴリ

質問済み:

2019 年 6 月 14 日

編集済み:

2019 年 6 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by