【问题标题】:MATLAB: locate the first position of each unique number from a vectorMATLAB:从向量中定位每个唯一数字的第一个位置
【发布时间】:2014-01-08 07:29:23
【问题描述】:

我希望从向量中找到每个唯一数字的第一个位置,但没有 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]

非常感谢

【问题讨论】:

    标签: arrays matlab vector element unique


    【解决方案1】:

    使用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 的大小要一致,则向量 A 中的每个数字必须至少出现 2 次(在您编辑之前不是这种情况)。

    【讨论】:

    • 但是第二次出现的位置呢?
    • @FF0605 如果每个数字恰好有两个出现,当然也可以通过定位最后一个元素找到第二个:[~,b] = unique(A)
    • @RodyOldenhuis 谢谢,简单而不错的尝试,您的帖子中有一个小错字“A = [1 1 2 2 3 4 2 1]”应替换为“a = [1 1 2 2 3 4 2 1 3 4]"
    • @DennisJaheruddin 谢谢,评论不应该是 [~,b] = unique(A,'last') 吗?
    • @FF0605:嗯,这就是你第一次发布它的方式 :) 我会更正它,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 2014-04-24
    • 2019-11-10
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多