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
This will work. @Steve pointed out an error in your updated solution.
After this,
elwill contain the first repeated element invandidxwill be its index inv.First you use stable unique to find the unique elements. The second output argument contains the original indices of each unique element. You then run
diff(Iv) - 1to find the jumps in the original indices. You usefind(, 1)to get the first element and add one to get the index in the original vector. Index into the original vector to get the element you want.