MATLAB:从向量中定位每个唯一数字的第一个位置



我希望从向量中找到每个唯一数字的第一个位置,但没有 for 循环:

例如

a=[1 1 2 2 3 4 2 1 3 4];

我可以通过以下方法获得唯一编号:

uniq=unique(a); 

其中 uniq = [1 2 3 4]

我想要的是获得每个数字的第一次出现位置,任何想法????

first_pos = [1 3 5 6] 
其中 1 首先出现在位置

1,4 首先出现在向量的第六个位置

另外,第二次出现的位置呢??

second_pos = [2 4 9 10]

谢谢

使用 unique 的第二个输出,并使用 'first' 选项:

>> A = [1 1 2 2 3 4 2 1 3 4];
>> [a,b] = unique(A, 'first')
a =
    1     2     3     4  %// the unique values
b =
    1     3     5     6  %// the first indices where these values occur

要查找第二次出现的位置,

%// replace first occurrences with some random number
R = rand;
%// and do the same as before
A(b) = R;
[a2,b2] = unique(A, 'first');
%// Our random number is NOT part of original vector
b2(a2==R)=[];
a2(a2==R)=[];

有了这个:

b2 =
    2     4     9    10

请注意,如果 bb2 的大小一致,则向量中的每个数字必须至少出现 2 次A(在您编辑之前不是这种情况)。

最新更新