Is it possible to use histc in for-loop?

1 view (last 30 days)
Markian  Petkov
Markian Petkov on 26 Mar 2014
Commented: Image Analyst on 26 Mar 2014
Hi all I am currently having some problems doing some tests for research. The general idea is having an array of X and Y values : X=[-3;-1;0;1;3] and Y=[0;0.3;0.5;0.7;1]. A 1000 times for-loop has to generate values of Y with rand(1) function and interpolate corresponding values of X from the arrays above. And a count has to be initiated to calculate what values fall in the interval X_int=linspace(-3,3) (which has 100 intervals). My suggestion is :
if true
% code
end
x=[-3;-1;1;3]; y=[0;0.3;0.5;0.7;1];
bin_ranges=linspace(-3,3);
for i=1:1000
yq_r=rand(1);
xq=interp1(y,x,yq_r,'linear','extrap');
bin_counts=histc(xq,bin_ranges)
end
Is it possible to use the histc function in this for-loop, because when I run it, it records only one value of increment (only one 1) in the bin_counts array and not 1000 different? Thank you in advance !

Answers (1)

Image Analyst
Image Analyst on 26 Mar 2014
You're only interpolating one value so xq will have only one bin with anything in it. Plus, for each iteration, you're just overwriting bin_counts, not adding to it. Maybe you want
bin_counts = bin_counts + histc(xq,bin_ranges);
though that's still an incredibly inefficient way of doing it instead of just creating the vector completely and then calling histc on the whole thing after you're done building it.
  2 Comments
Markian  Petkov
Markian Petkov on 26 Mar 2014
How am I meant to create this vector (you mean vector of values of xq, right). I thought the same, but I couldn't actually realised how to do it... :? Thanks
Image Analyst
Image Analyst on 26 Mar 2014
You can pass in an array as the third argument to interp1. Get rid of the loop in that case - the case where you pass in rand(1,1000) instead of yq_r.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!