Reputation: 4664
In matlab I have two different matrices.
The one is for example
A =[34.5, 35.8, 24.5, 32.3;
23.4, 33.1, 31.2, 14.6];
And the second is:
B =[34.5, 32.3; 36.7
23.4, 14.6, 65.1];
I want to get a new one containing only the same values per column,
e.g. C =[34.5, 32.3;
23.4, 14.6];
Matrices A and B do not have the same number of columns.
Is there any matlab's function or can you help me to resolve this?
Upvotes: 2
Views: 1062
Reputation: 221514
This diff
based approach could be more efficient -
%// Concatenate A and B
AB = sortrows([A B].') %//'
%// Use DIFF to get a logical array of repetitions and
%// use that to select elements from AB
out = unique(AB([false ; ~any(diff(AB,[],1),2)],:),'rows').'
You can replace the last line with something like this -
out = AB(strfind([false ; ~any(diff(AB,[],1),2)].',[0 1]),:).'
For an elegant solution, I think intersect
based solution as suggested in the comments might suit -
out = intersect(A.',B.','rows','stable').'
Upvotes: 2
Reputation: 112659
You could also use:
result = B(:,any(pdist2(A.', B.')==0, 1));
Upvotes: 1