MATLAB Answers


How to get rid of repeating values inside an array

Asked by Rokki
on 19 Sep 2017
Latest activity Edited by Andrei Bobrov
on 21 Sep 2017
I have a matrix
a=[1 2 3 3 4 4 5];
I want to get rid of values 3 and 4 as they are repeating so that the output becomes
b=[1 2 5]


Sign in to comment.

2 Answers

Answer by José-Luis
on 19 Sep 2017
Edited by José-Luis
on 19 Sep 2017
 Accepted Answer

b = a(sum(bsxfun(@eq,a,a'))==1)


Thank you very much
My pleasure.
Please keep in mind that this is inefficient for large arrays though. Just using unique() should take you where you need to go.

Sign in to comment.

Answer by Andrei Bobrov
on 19 Sep 2017
Edited by Andrei Bobrov
on 21 Sep 2017

v = unique(a);
b = v(histcounts(a,[v(:);v(end)+eps]) == 1);
v = unique(a);
b = v(histc(a,v) == 1);
aa = sort(a);
t = diff(aa);
b = aa([1 t] & [t 1]);


Thank you for help. I am getting an error
Undefined function 'histcounts' for input arguments of type 'double'.
histcounts() was introduced with R2014b. You don't need it though. unique() is enough. Andrei was giving you two alternatives.

Sign in to comment.