how to use unique command for the structured array

26 views (last 30 days)
How do I use unique command for a structured array and do the that only based on data of one part of that array. for example:
"a" is a struct array with fields:
z
fit
and
a(1).fit = [5;7]
a(2).fit = [3;8]
a(3).fit = [5;7]
a(1).z = 'Sunday'
a(2).z = 'Monday'
a(3).z = 'Tuesday'
I want to delete the repetitive raw 3, i.e. "a(3).fit = [5;7]" from structure array and its related raw which is "a(3).z = 'Tuesday'" to have :
a(1).fit = [5;7]
a(2).fit = [3;8]
a(1).z = 'Sunday'
a(2).z = 'Monday'
  2 Comments
Guillaume
Guillaume on 26 Oct 2016
Edited: Guillaume on 26 Oct 2016
a.fit(1) = [5;7]
is not valid matlab (you're assigning two elements 5 and 7 to a single element fit(1)). The same is true of a.z(1) = somevector.
Did you actually mean
a(1).fit = [5;7]
a(2).fit = [3;8]
a(3).fit = [5;7]
which would make a a 3x1 or 1x3 struct array with scalar fields?
meh alipoo
meh alipoo on 26 Oct 2016
Thank you for your comment you are true I edit my mistake

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 26 Oct 2016
Edited: Guillaume on 26 Oct 2016
Assuming you actually meant a structure such as the one created by:
a = struct('fit', {[5;7], [3;8], [5;7]}, 'z', {'Sunday', 'Monday', 'Tuesday'})
Then the following will work:
[~, idx] = unique([a.fit].', 'rows', 'stable'); %stable optional if you don't care about the order.
a = a(idx)
[a.fit] concatenates the columns in each a.fit to make a single matrix (so all the columns must be the same size). It's then transposed so that unique can work on the rows (formerly columns). The 2nd return value of unique gives you the indices of the rows that were kept, which are the indices of the structure elements to keep.

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!