Find unique values of a vector with same order as in the vector in matlab

后端 未结 3 1468
执笔经年
执笔经年 2021-01-19 14:03

I have a vector A=[2,5,6,2,4,13,34,3,34]. I want to find a unique value of this vector but not in sorted order! I searched in Matlab site and I found this function

相关标签:
3条回答
  • 2021-01-19 14:13
    A=[2,5,6,2,4,13,34,3,34];
    [B, ia] = sort(A);     % B = A(ia)
    ib(ia) = 1:length(B);  % A = B(ib)
    [C, ic] = unique(B);   % C = B(ic)
    D = B(ib(ic));         % unsorted unique values
    
    0 讨论(0)
  • 2021-01-19 14:16

    Assuming you have a vector (so the 'rows' version makes no sense), here's a solution based on bsxfun:

    [~, ind] = max(bsxfun(@eq, A, A.'));
    ind = ind(ind>=1:numel(ind));
    C = A(ind);
    

    How it works: Do all pairwise comparisons between elements (bsxfun(@eq, A, A.')). For each element, find the index of the first equal element ([~, ind]=max(...)). If that index is smaller than the current position (that is, if there's a previous element which is equal to the current one), disregard it (ind = ind(ind>=...). Use the surviving indices to generate the result (C = A(ind)).

    0 讨论(0)
  • 2021-01-19 14:16

    Here's an implementation if you are working with 2D arrays and would like to get the same functionality as unique(A,'rows','stable') -

    function [C, ia, ic] = unique_rows_stable(A)
    
    [unqmat_notinorder,row_ind,labels] = unique(A,'rows','first');
    
    [ia,ordered_ind] = sort(row_ind);
    
    C = unqmat_notinorder(ordered_ind,:);
    
    [~,ic] = ismember(labels,ordered_ind);
    %// Or [ic,~] = find(bsxfun(@eq,ordered_ind,labels'))
    
    return;
    
    0 讨论(0)
提交回复
热议问题