Using accumarray to create histograms from random integers

조회 수: 5 (최근 30일)
Luke S
Luke S 2011년 10월 18일
Hi,
I'd like to create N histograms, each from a dataset of n_vals random integers from 1 to h_length. I can demonstrate my goal for N=1 using accumarray:
N=1;
h_length=10000;
n_vals=900;
%create n_vals random integers between one and h_length
inds=floor((h_length)*rand(n_vals,N)+1);
rand_hists=accumarray(inds,1,[h_length,1]);
%this plot demonstrates the output.
figure;plot(rand_hists)
However, I'm not sure how to do this for an N larger than 1. Ultimately, I want N~=2000. I'm pretty sure I will have a memory limitation and have to do some looping, but I would like to vectorize and do it as efficiently as possible.
Any advice is greatly appreciated.
Thanks, Luke
Comment on this

채택된 답변

Fangjun Jiang
Fangjun Jiang 2011년 10월 18일
Check to see if you have these function.
randi()
hist()
  댓글 수: 1
Luke S
Luke S 2011년 10월 18일
I have both! randi() I didn't know about before, and it seems to save a little bit of time over floor(randn()).
Using histc() can operate on an Nxh_length array of inds as I wanted, but it actually seems o be ending up slower than looping over accumarray N times.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Peter Perkins
Peter Perkins 2011년 10월 19일
Luke, I'm not exactly sure what you're asking, but as I interpret it, you want a single call to accumarray to create N sets of counts. You may find that this is no faster than a loop around accumarray, but the following code is what I think you're looking for. It passes accumarray 2-D indices (which can be done in two different ways, here I used separate column vectors), where the second index is just an "indicator variable that says which "set" of counts a given row should be put in.
I've replaced your call to rand with randi, and I'm not sure what you're plot was supposed to be doing, but I more or less kept it as is.
N=3;
h_length=10000;
n_vals=900;
%create n_vals random integers between one and h_length
iinds = randi(h_length,n_vals,N);
jinds = repmat(1:N,n_vals,1);
rand_hists = accumarray({iinds(:) jinds(:)},1,[h_length,N]);
%this plot demonstrates the output.
for i = 1:N
subplot(N,1,i), plot(rand_hists(:,i),'.')
end

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by