how to use unique command for the structured array
25 次查看(过去 30 天)
显示 更早的评论
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 个评论
Guillaume
2016-10-26
编辑:Guillaume
2016-10-26
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?
采纳的回答
Guillaume
2016-10-26
编辑:Guillaume
2016-10-26
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.
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!