MATLAB: How to efficiently find the indices

efficiencymatrixunique

Hi,
I have a matrix of N-by-M with integers. I need to efficiently find the indices for all of the unique elements in the matrix. The solution I have is via a "for" loop:
uM = unique (M(:));
for i = 1 : length(uM)
I(i) = find(M == uM(i));
end
This works fine, but with a large matrix, this is slow. I wonder if there are better solutions. thanks very much!

Best Answer

sort is your friend:
First we sort the entries of A so that like entries are adjacent
[S, iSorted] = sort(A(:));
Then we find the markers - where the value changes, plus the endpoints
markers = [0; find(diff(S)); numel(A)];
All we need to do is find the entries of iSorted corresponding to each block.
for i = 1:numel(markers)-1
uM(i) = S(markers(i)+1);
I{i} = iSorted(markers(i)+1:markers(i+1));
end