How to find repeated values in a matrix?
2 views (last 30 days)
Show older comments
I am trying to obtain the repeated values in each row from a matrix and then store it in a separate matrix. I'm thinking of using unique and histc functions to do so.
Q = [ 27.1028 32.3493 28.5714 28.5714; 17.1429 17.1429 18.4581 12.9200]
The repeated values in row 1 is 28.5712, in row 2 it is 17.1429. I want to obtain these values so P = [28.5712; 17.1429]. One problem I'm facing is using the unique function. unique(Q) gives me ALL the values. Why is it so?
0 Comments
Accepted Answer
Rik
on 19 May 2017
Are repeated values always next to each other? If so you can use diff(Q,1,2) to find the positions that have repeated values. (about that syntax: the 1 is the number of times diff will be run recursively, the 2 is the dimension along which diff should operate)
unique gives all values that occur in the vector/matrix, which is about the opposite of what you want. You can however use that: unique can return the indices of the values it finds. You can then find out what indices are missing to find the repeated values. This method relies on values not occuring in multiple rows and doesn't keep information about in which row the values were (except in idx)
Q = [ 27.1028 32.3493 28.5714 28.5714; 17.1429 17.1429 18.4581 12.9200];
[C,idx]=unique(Q,'stable');%don't sort
idx=setxor(idx,1:numel(Q));
repeating_values=Q(idx);
2 Comments
Stephen23
on 19 May 2017
@Atiqah Zakirah: your code tests for equivalence of floating point values, which is a very buggy and unreliable way to write code. You need to change your algorithm to take into account floating point error:
etc, etc, etc
More Answers (0)
See Also
Categories
Find more on Line Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!