MATLAB: Relabel the arrays’ elements with an increasing order

arrayelementsincreasing orderrelabel

Hi, I have this array:
A = [3 3 3 3 1 1 4 4 4 4 2 2 2]
and I need to relabel those elements with an increasing order, as follows:
B = [1 1 1 1 2 2 3 3 3 3 4 4 4]
Do you know any more compact solution than mine (here below)?
B = zeros(1,length(A));
[~,startunique] = unique(A);
c = sort(startunique);
for i = 1 : length(c)
B(find(A==A(c(i)))) = i;
end

Best Answer

  • Try this
    A = [3 3 3 3 1 1 4 4 4 4 2 2 2];
    [~, ~, B] = unique(A, 'stable');
    Result
    >> B
    B =
    1
    1
    1
    1
    2
    2
    3
    3
    3
    3
    4
    4
    4