how to extract similar columns from different matrices

1 view (last 30 days)
Dear,
I have tow matrices with different size and I need to get the similar columns from the first on.
a=[
0 0 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 1 1 1 1 0
1 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1 1
1 1 0 0 0 0 0 0 0 0 0 0 0 0]';
b=[
0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]';
they have the same size of rows. I tried this
tf = ismember(C, a(ismember(a,b,'rows')), 'rows')
result = C(tf,:)
I take the transpose for the matrices but there is an error, I used intersect command but is the same.
can anyone help me please I will be grateful.
regards,
Reway

Accepted Answer

Guillaume
Guillaume on 3 Jul 2015
Possibly, in your first expression you meant to have
a(ismember(a, b, 'rows'), :) %rather than a(ismember(a,b,'rows'))
But if you don't care about not getting the duplicate rows in a, then:
intersect(a, b, 'rows')
is simpler.
You haven't showed C in your example. Possibly, all you want is this:
result = intersect(C, intersect(a, b, 'rows'), 'rows')
Note that if you get an error, tell us what the exact error message is.
  7 Comments
Thorsten
Thorsten on 6 Jul 2015
Edited: Thorsten on 6 Jul 2015
To get the row index of all rows in a that also appear in b, use
idx = ismember(a,b,'rows');
Now you use this logical row index and extract the corresponding rows from a:
commonrows = a(idx, :);
You can write both commands in one line:
commonrows = a(ismember(a, b, 'rows'), :);
which is precisely what Guillaume suggested.
If that's not what you want, please try to rephrase your question.
rewayda mohsin
rewayda mohsin on 7 Jul 2015
Thanks Thorsten,
I think yes Guillaume gave me what I asked exactly but I messed this
idx = ismember(a,b,'rows');
I didn't notice its the index, I expected to get the index of the column in the matrix as a number of the column.
many thanks,
regards,

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!