Linking values in two matrices
显示 更早的评论
Hi, Complete Newbie!
I want to compare two matrices let's say A and B if A = [1 0 3 0 2 5 ] and B = [0 2 5 0 2 10 ]. I need to work out for any cell in A>0 is the corresponding cell in B filled (i.e. >0) (for now it doesn't matter what the difference in value is, but just whether the cells are filled or not). In addition, I want to know if a cell in A is equal to 0 is the corresponding cell in B also equal to 0. I then want to count the number of times that the cells match i.e. how many times in A and B were both the cells filled or both = 0?
Any suggestions much appreciated!
回答(1 个)
A > 0 & B > 0
A == 0 & B == 0
Counting the results is trivial.
6 个评论
Aoife Cordon
2017-5-8
Walter Roberson
2017-5-8
You can combine the tests:
match = (A > 0) == (B > 0);
You mention filled is A > 0, and you mention 0. If you are either sure that you will never have negatives, or if you want negatives to be considered filled as well, then you can use
match = logical(A) == logical(B)
and if you do not mind being a bit obscure, that can be written
match = ~A == ~B;
Aoife Cordon
2017-5-8
Walter Roberson
2017-5-8
"if I understand correctly this simply tells me if the values are equal"
No, A > 0 & B > 0 is true in locations where both items are filled. A > 0 is 0 for empty items and 1 for filled items, and the & operator is true only if both corresponding items are non-zero .
In the case where you do not have negative values, A > 0 & B > 0 can be abbreviated as A & B, which means the same thing as (A ~= 0) & (B ~= 0)
Aoife Cordon
2017-5-9
编辑:Aoife Cordon
2017-5-9
Walter Roberson
2017-5-9
"I only want it to compare the four cells which are filled in A with the corresponding cells in B"
B(A>0)>0
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!