How to use ISMEMBER when not all rows match

2 views (last 30 days)
I'm trying to dynamically update and compare values corresponding to their respective ID. This problem is easy if all ID's are same each time (use horzcat). The problem is that not all ID's are represented each time. For these, I want the value corresponding to the ID to be 0. See simple example below:
A=[1 2 3 4 5 6; 1 1 1 1 1 1]'
B=[2 3 4;2 2 2]'
where A(:,1) and B(:,1) refer to the ID; so A and B share 2 3 4 in common and A(:,2) and B(:,2) are values in two different time periods, i.e., value of ID=2 is 1 in t=1 and 2 in t=2. But elements 1, 5, 6 didn't occur in time period 2.
I want the result:
compare=[1 2 3 4 5 6;1 1 1 1 1 1;0 2 2 2 0 0]'
So it fills in zeros if the ID is not represented in B. If you use:
[~,idx]=ismember(A,B,'rows')
you get:
idx =
0
1.00
2.00
3.00
0
0
But rather than the index, I want it to fill in the values of B(:,2) that match in their respective row.

Accepted Answer

Titus Edelhofer
Titus Edelhofer on 18 Mar 2013
Hi Sophia,
what about this?
compare = [A zeros(size(A,1),1)]
[ismemb,idx] = ismember(A(:,1), B(:,1))
compare(ismemb,3) = B(idx(ismemb))
Does this help?
Titus

More Answers (0)

Tags

Products

Community Treasure Hunt

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

Start Hunting!