user1245262
user1245262

Reputation: 7505

How can I perform a union with two single-field Matlab structs

I currently have two single-field Matlab structs that list image names. I would like to combine them into a single struct with no duplicates - i.e.

a(1).img = 'aa.jpg'
a(2).img = 'bb.jpg'

b(1).img = 'bb.jpg'
b(2).img = 'cc.jpg'

I would like for ab to have value(s):

ab(1) = 'aa.jpg'
ab(2) = 'bb.jpg'
ab(3) = 'cc.jpg'

Is there a non=brute force way of doing this?

Upvotes: 3

Views: 113

Answers (1)

Suever
Suever

Reputation: 65430

You can concatenate the values from each of the structs using a comma-separated list followed by unique to get the unique values. Then, passing this to the struct function will create an array of structs containing the values.

S = struct('img', unique({a.img, b.img}, 'stable'))

If you don't actually need a struct out and just want a cell array of the unique values, you can eliminate the final call to struct.

unique({a.img, b.img}, 'stable')

Upvotes: 3

Related Questions