How to pull values out of a matrix using another matrix?

2 ビュー (過去 30 日間)
tban
tban 2017 年 4 月 9 日
コメント済み: Walter Roberson 2017 年 4 月 10 日
Matrix_One:
[0 1 1 0;
1 1 0 0;
0 0 0 1;
1 0 0 0]
Matrix_Two:
[9 3 1 9;
3 6 1 9;
2 0 6 4;
2 6 4 8]
What I want:
[0 3 1 0;
3 6 0 0;
0 0 0 4;
2 0 0 0]
Basically eliminate every value from initial matrix 2 beside where the ones are in matrix 1. I tried putting one matrix within another and it doesn't work.
  1 件のコメント
per isakson
per isakson 2017 年 4 月 9 日
編集済み: per isakson 2017 年 4 月 9 日
  • Click the Help button above the edit-box, in which you write your question.

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

回答 (3 件)

Walter Roberson
Walter Roberson 2017 年 4 月 9 日
matrix2(matrix1==0) = 0;

Star Strider
Star Strider 2017 年 4 月 9 日
Try this:
M1 = [0 1 1 0;
1 1 0 0;
0 0 0 1;
1 0 0 0];
M2 = [9 3 1 9;
3 6 1 9;
2 0 6 4;
2 6 4 8];
Wanted = M2 .* M1
Wanted =
0 3 1 0
3 6 0 0
0 0 0 4
2 0 0 0
  2 件のコメント
tban
tban 2017 年 4 月 9 日
very creative
Star Strider
Star Strider 2017 年 4 月 9 日
... and it gives the desired result!

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


David Goodmanson
David Goodmanson 2017 年 4 月 9 日
編集済み: David Goodmanson 2017 年 4 月 9 日
Hello Tudor, Here is one way:
indx = find(matrix1==0)
matrix2(indx) = 0
This works because 'find' looks at the elements of matrix1 columnwise in a running index from (in this case) 1 to 16, and the second line reads them back in the same way.
In this specific case you could multiply the two matrices by each other elementwise, but that way is a lot less versatile. In general maybe you would want to set the mat2 elements corresponding to mat1 = a to value b and you can't do that with elementwise multiplication.
  1 件のコメント
Walter Roberson
Walter Roberson 2017 年 4 月 10 日
Element-wise multiplication:
matrix2 = matrix2 .* (matrix1 ~= 0);

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by