MATLAB: Comparison of the fields of two structures with a condition

struct

I need to compare values of two fields of two different structures but with a condition on two other fields of these structures.
suppose that these are the two structures that I want to compare:
a=struct('field1',{},'field2',{},'field3',{})
b=struct('field1',{},'field3',{},'field4',{})
(Of course they're both filled)
I want to comapre values of a.field1 and b.field1 if they are equal then I'll calculate a.field2 – b.field2, after that I have to find max(a.field2 – b.field2)
how can I do it ?

Best Answer

If all the fields are scalar, you don't need any special function. I'm assuming that there can be at most one i and j for which a(i).field1 == b(j).field1. If not, you need to explain which (i, j, or both) can be duplicate and what needs to be done in that case
[~, ia, ib] = intersect([a.field1], [b.field2]); %find location of matching field1 elements of both structure array
maxValue = max([a(ia).field2] - [b(ib).field2])