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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With