how to remove the repetitive elements from a structure

>> a = struct('position', {[200 300 1],[300 200 1],[250 250 0.5],[230 280 0.6],[300 200 1],[270 150 1]}, 'cost', {[50;90],[60;80],[65;89],[60;70],[60;80],[55;85]})
I have a structure with two fields, I need to two remove the duplicates?
I tried useing the code below but it did not work.
[~, idx] = unique([a.position].', 'rows', 'stable'); %stable optional if you don't care about the order.
a = a(idx)
I hope I can find a sulotion for this problem.

Answers (1)

Data:
>> a = struct('position', {[200 300 1],[300 200 1],[250 250 0.5],[230 280 0.6],[300 200 1],[270 150 1]}, 'cost', {[50;90],[60;80],[65;89],[60;70],[60;80],[55;85]});
>> a.cost
ans =
50
90
ans =
60
80
ans =
65
89
ans =
60
70
ans =
60
80
ans =
55
85
Then remove duplicates:
N = numel(a);
X = false(1,N);
for ii = 2:N
Y = false;
for jj = 1:ii-1
Y = Y || isequal(a(ii),a(jj));
end
X(ii) = Y;
end
a(X) = []
Giving (fifth element has been removed):
>> a.cost
ans =
50
90
ans =
60
80
ans =
65
89
ans =
60
70
ans =
55
85

2 Comments

Thank you so much Stephen, I appreciate your time answering my question, and i found it so helpful.
Related to this question I would like to ask; what if there are repetitive elements in only one filed of the structure but no repetition in the other. Would it be easy to delete the duplicated element with its corresponding element from the other field?
a = struct('position', {[200 300 1],[300 200 1.5],[250 250 0.5],[230 280 0.6],[300 200 1],[270 150 1]}, 'cost', {[50;90],[60;80],[65;89],[60;70],[60;80],[55;85]});
alright, I think I found the answer,
N = numel(a);
X = false(1,N);
for ii = 2:N
Y = false;
for jj = 1:ii-1
Y = Y || isequal(a(ii).cost,a(jj).cost);
end
X(ii) = Y;
end
a(X) = []
thank you

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

No tags entered yet.

Asked:

on 20 Apr 2019

Commented:

on 21 Apr 2019

Community Treasure Hunt

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

Start Hunting!