Counting occurrences of a pointer

1 回表示 (過去 30 日間)
Alvin Stroyny
Alvin Stroyny 2013 年 8 月 5 日
n=5;
h=zeros(n,1);
u=ceil(rand(n,1)*n); % random sample on (1,n) with replacement
h(u) = h(u) +1;
u = [3 4 1 1 5]]
h = [1 0 1 1 1]
note h(1) = 1 not 2 even though there are 2 occurrences of 1 in u
I know the following loop will count properly
for i=1:n
h(u(i)) = h(u(i)) +1;
end
How can I code this a a vector operation without a loop?

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 8 月 5 日
編集済み: Azzi Abdelmalek 2013 年 8 月 5 日
u = [3 4 1 1 5]
accumarray(u',[1:numel(u)]',[],@(x) numel(x))
  1 件のコメント
Jan
Jan 2013 年 8 月 5 日
The additional square brackets are not needed and waste time only:
[1:numel(u)]' ==> faster: (1:numel(u))'

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

その他の回答 (0 件)

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by