MATLAB: How to find index of duplicate values in a matrix

duplicateindexmatrix

Hi, I have a matrix A = [1 2 3 ; 4 2 3] I would like to know the i and j index of the duplicate values in this matrix. How could I do ? The output should be something like {2 ; [1 2]; [2 2]} {3 ; [1 3]; [2 3]} Thanks for your help, Guilhem

Best Answer

Your example output (a 3x2 cell array) can only work if the numbers of repeat is the same for all repeated values. Otherwise you'll need a cell array of cell array. Furthermore, in general it's not a good idea to keep a [row, column] pair of indices, a linear index is more usually more useful.
Here is how I'd go about obtaining something similar to your desired output, that works regardless of the number of repeats:
A = [1 2 3 ; 4 2 3];
[uvalues, ~, uid] = unique(A(:));
count = accumarray(uid, 1); %easiest way to calculate the histogram of uvalues

linindices = accumarray(uid, (1:numel(A))', [], @(idx) {idx}); %split linear indices according to uid
valwhere = [num2cell(uvalues), linindices]; %concatenate
valwhere(count == 1, :) = [] %remove count of 1
The above gives you the list of linear indices. If you do really want the (row, column pairs):
A = [1 2 3 ; 4 2 3];
[uvalues, ~, uid] = unique(A(:));
count = accumarray(uid, 1); %easiest way to calculate the histogram of uvalues
[rows, cols] = ind2sub(size(A), (1:numel(A))');
rowcols = accumarray(uid, (1:numel(A))', [], @(idx) {num2cell([rows(idx), cols(idx)], 2)'});
valwhere = [num2cell(uvalues), rowcols];
valwhere(count == 1, :) = []