How do I generate histogram of values in a vector, n bins, spread uniformly in an interval [a,b]?

I cannot use the hist function, I am asked to generate my own m-function, in the form of myfunction(v,a,b,n) where v is the vector where the data is stored and n is the number of bins. I produced this function histarray=myhist(v,a,b,n) histarray=zeros(1,n); dx=(b-a)/n; x=0:dx:n-1; for i=1:length(v) histarray(1,v(i)+1)=histarray(1,v(i)+1)+1; end bar(x,histarray) end The error that comes up is either that the vecotr are not the same length or double arguments. I am not sure what I am doing wrong, but I have a feeling its somewhere in the loop. I would be grateful for any help.

Answers (1)

The line "histarray(1,v(i)+1) = histarray(1,v(i)+1)+1;" is in error. You need to figure out some way to add 1 to the bin corresponding to v(i), but that doesn't do it. The value v(i)+1 will probably not even be an integer, so it would be invalid as a vector index. Trying writing some numbers down on paper using some simple fractional values in v to see what is involved in placing counts in the right bins.

Asked:

on 2 Mar 2014

Answered:

on 2 Mar 2014

Community Treasure Hunt

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

Start Hunting!