Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the intersection of two array structs in Matlab

How can I find the following intersection of two array structs in Matlab.

For example, I have two struct arrays a and b:

a(1)=struct('x',1,'y',1);
a(2)=struct('x',3,'y',2);
a(3)=struct('x',4,'y',3);
a(4)=struct('x',5,'y',4);
a(5)=struct('x',1,'y',5);


b(1)=struct('x',1,'y',1);
b(2)=struct('x',3,'y',5);

I want to find the intersection of a and b as follows:

c = intersect(a,b)

where c should be

c = struct('x',1,'y',1);

But when it seems wrong when I type intersect(a,b) since the elements of a and b are both structures. How can I combat this difficulty. Thanks.

like image 566
John Smith Avatar asked Jan 14 '23 06:01

John Smith


1 Answers

The elegant solution would have been to supply intersect with a comparator operator (like in , e.g., C++).
Unfortunaetly, Matlab does not seem to support this kind of functionality/flexibility.

A workaround for your problem would be

% convert structs into matrices
A = [[a(:).x];[a(:).y]]';
B = [[b(:).x];[b(:).y]]';
% intersect the equivalent representation
[C, ia, ib] = intersect( A, B, 'rows' );
% map back to original structs
c = a(ia);

Alternatively, have you considered replacing your structs with class objects derived from handle class? It might be possible to overload the relational operators of the class and then it should be possible to sort the class objects directly (I haven't looked closely into this solution - it's just a proposal off the tip of my head).

like image 72
Shai Avatar answered Jan 21 '23 23:01

Shai