フィルターのクリア

How can I map to each vector entry a number telling its occurence so far?

2 ビュー (過去 30 日間)
Marcel Beining
Marcel Beining 2018 年 7 月 25 日
コメント済み: Guillaume 2018 年 7 月 25 日
I have a vector
vec = [1,2,3,4,2,5,2,3];
and I want to have the output
[1,1,1,1,2,1,3,2]
so that each number tells me how often the value so far has occurred in the vector. Is there any possibility to do this without a for/while loop?

採用された回答

Stephen23
Stephen23 2018 年 7 月 25 日
編集済み: Stephen23 2018 年 7 月 25 日
No third-party functions required, four lines of code:
>> vec = 5+[1,2,3,4,2,5,2,3];
>> [uni,~,idx] = unique(vec);
>> tmp = cell2mat(arrayfun(@(n)1:n,histc(vec,uni),'uni',0));
>> [~,idy] = sort(idx);
>> tmp(idy) % code output
ans =
1 1 1 1 2 1 3 2
>> [1,1,1,1,2,1,3,2] % requested output
ans =
1 1 1 1 2 1 3 2
  1 件のコメント
Guillaume
Guillaume 2018 年 7 月 25 日
I would argue that arrayfun is a loop.
While it is indeed shorter, it is also about 4 times as slow on my machine. On the other hand both take less than half a second for a 1e6 element vector, so it doesn't really matter.

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

その他の回答 (2 件)

Guillaume
Guillaume 2018 年 7 月 25 日
編集済み: Guillaume 2018 年 7 月 25 日
It can be done without a loop, however for part of the code I recommend you use rcumsum from the FileExchange instead of what I've done here:
vec = [1,2,3,4,2,5,2,3];
[ordervec, indices ] = sort(vec); %group indentical values together and store their original position
issameasprevious = [0, ~diff(ordervec)];
%the following lines can be replaced by
%runlength = rcumsum(issameasprevious) + 1;
%otherwise:
zeroloc = ~issameasprevious;
runlength = cumsum(issameasprevious); %compute temporary cumsum with no reset
issameasprevious(zeroloc) = -diff([0 runlength(zeroloc)]); % how much to subtract at 0 values?
runlength = cumsum(issameasprevious) + 1; %recompute cumsum which no reset at 0
result = runlength(indices) %reorder according to original order
edit: typo in the code
  1 件のコメント
Guillaume
Guillaume 2018 年 7 月 25 日
Note: my recommendation to use rcumsum apply if you're going to use the compiled mex version of it. It's optional and if you don't the code is exactly equivalent to what I've written (except it's going to be slower because of the input checks).
If you use the mex version of rcumsum then the above is going to be much faster than alternative solutions (and is also just 4 lines of code)

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


Udit Dhand
Udit Dhand 2018 年 7 月 25 日
I wasnt able to do it without using while loop
vec = [1,2,3,4,2,5,2,3];
j=length(vec);k=0;
while k~=j
o = find(vec==vec(j-k));
i=1:length(o);
out(o)=i;
k=k+1;
end

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品


リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by