Increase counter for each element in array

Hey,
given A = [1 1 3 4 5 6 6 7 7 7]. How could I return the sequence B =[1 2 1 1 1 1 2 1 2 3] such that each duplicate is counted and B is the same size as A?
I appreciate your help!

 採用された回答

madhan ravi
madhan ravi 2020 年 6 月 17 日

2 投票

ix = A(:) == unique(A);
B = nonzeros(cumsum(ix) .* ix)

6 件のコメント

Dario Walter
Dario Walter 2020 年 6 月 17 日
Really nice solution madhan. It works nicely for small arrays of A. Yet, A is a vector of 70000 entries in my case. Your approach results in an out of memory error :/
madhan ravi
madhan ravi 2020 年 6 月 17 日
u = unique(A);
B = cell(1,numel(u));
for k = 1:numel(u)
ix = A == u(k);
B{k} = nonzeros(cumsum(ix) .* ix).';
end
B = [B{:}];
KSSV
KSSV 2020 年 6 月 18 日
編集済み: KSSV 2020 年 6 月 18 日
+1 I don't know this....(For the first answer)
Dario Walter
Dario Walter 2020 年 6 月 18 日
編集済み: Dario Walter 2020 年 6 月 18 日
Hey, thanks for your help so far. This approach only works for sorted data (which I am not allowed to do in my approach). Bad example I chose, sorry for that. What about B = [4 4 3 3 3 2 2 1 1 7 7 9 9] (each unique number only appears in a sequence in my problem, so that, for instance, C = [4 4 3 4] does not exist.
[B,I] = sort(A,'ascend') does neither help.
madhan ravi
madhan ravi 2020 年 6 月 18 日
I knew you would come up with that question. That’s why you should experiment with 'stable' option in unique function.
Dario Walter
Dario Walter 2020 年 6 月 18 日
Well done Madhan :). Thanks a lot!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLicensing on Cloud Platforms についてさらに検索

製品

リリース

R2020a

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by