我想找到出现在向量中先前位置的第一个元素。
例如,如果向量是:
v = [1, 3, 2, 3, 4, 5];
答案是v(4) = 3
,因为 3 是第一个出现两次的元素。
有没有办法向量化这个操作?
更新:
这是我目前的解决方案,您有更好的建议吗?
[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)
是出现两次的第一个元素的索引。
新更新:
按照@mwengler 的解决方案,我现在提出解决方案来找到矩阵每一行的第一个重复元素。
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