2

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?

Divakar
  • 218,885
  • 19
  • 262
  • 358
zinon
  • 4,427
  • 14
  • 70
  • 112
  • So, it might well end up with different number of common elements per row, so you would need a cell array as output, right? – Divakar Apr 06 '15 at 21:16
  • @Divakar Sorry, I mean columns not rows! I edited my question. – zinon Apr 06 '15 at 21:18
  • 1
    How about this `intersect(A.',B.','rows','stable').'`? – Divakar Apr 06 '15 at 21:19
  • @Divakar Thank you, that's it! And then I just transponse the columns to rows. – zinon Apr 06 '15 at 21:24
  • Yes, that's being done in it. Also, you might find this useful - [`Faster alternative to INTERSECT with 'rows' - MATLAB`](http://stackoverflow.com/questions/28493795/faster-alternative-to-intersect-with-rows-matlab). – Divakar Apr 06 '15 at 21:26

2 Answers2

2

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').'
Divakar
  • 218,885
  • 19
  • 262
  • 358
1

You could also use:

result = B(:,any(pdist2(A.', B.')==0, 1));
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147