我想查找出現在矢量中以前位置的第一個元素。如何查找在矢量中看到兩次的第一個元素
例如,如果載體是:
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
在您更新的解決方案上,我會指出,對於v = [1 3 4 4 3 5],您將得到答案5,因爲代碼不返回_first_重複,它返回_smallest_重複(因爲排序) – Steve
好點子。謝謝! – Fashandge