MATLAB: How to find repeated values in a matrix

histcmatrixrepeated valuesrowsunique

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?

Best Answer

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);