I want to find the first element that has appeared in previous positions in a vector.
For example, if the vector is:
v = [1, 3, 2, 3, 4, 5];
the answer is v(4) = 3
, since 3 is the first element that has been seen twice.
Is there a way to vectorize this operation?
Update:
Here's my current solution, do you have better suggestions?
[s o] = sort(v); % sort the array
d = diff(s); % the first zero corresponds to the first repetitive element
d = find(d == 0);
o(d(1) + 1)
is the index of the first element that has been seen twice.
New Update:
Following @mwengler's solution, I now come up the solution to find the first repeated element of each row of a MATRIX.
function vdup = firstDup(M)
[SM Ord] = sort(M, 2); % sort by row
[rows cols] = find(~diff(SM, 1, 2)); % diff each row, and find indices of the repeated elements in sorted rows
Mask = (size(M,2) + 1) * ones(size(M)); % create a Mask matrix with all size(M,2)+1
ind = sub2ind(size(Ord), rows, cols+1); % add 1 to the column indices
Mask(ind) = Ord(ind); % get the original indices of each repeated elements in each row
vdup = min(Mask, [], 2); % get the minimum indices of each row, which is the indices of first repeated element