comparison of the fields of two structures with a condition

34 views (last 30 days)
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 ?
  3 Comments
Walter Roberson
Walter Roberson on 16 Jan 2019
Are the field to be compared numeric scalars? Are they character vectors? Are they numeric arrays? Are they transfer functions? You asked for efficiency, but the efficiency that can be achieved is going to depend upon the datatypes and sizes involved.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 16 Jan 2019
Edited: Guillaume on 16 Jan 2019
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])
  3 Comments
Guillaume
Guillaume on 16 Jan 2019
Yes, it's not very clear if it needs to be matching indices of a and b that need to be equal, or any index. The structfind indeed points toward the latter.
As I said, my answer only works if there's at most a one-to-one match. If not, it's going to be more complicated but it's not clear at the moment if it can be the case. The given code seem to allow for duplicate b but I'm not sure if it's on purpose.

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!