简体   繁体   中英

Histogram plot in Matlab with constraints

I want to plot a histogram with the following outputs:

   (a). number of bin
   (b). data in each bin
   (c). bin size for each bin
   (d). bin start & bin end for each bin

Each bin must have at least 7 elements. I gave a try something like this

  data = rand(100,1);
  n = hist(data);

This will give result like this

  10     8    12    12    10     3    10    12    12    11

When I tried

  n = hist(data,7);

I got

  15    14    17     9    11    16    18

& this is exactly what I want, with at least 7 elements in each bin! & at the same time I also want to cover part (c) & (d).

So, to be already sure that I am getting the right number of elements in each bin, I tried like this:

  data = rand(100,1);
  i = length(data);
  n = hist(data, i);
  min_number = 7;   % minimum no. in each bin
  for j = 1:length(n)
     if n(j) < min_number
      i = i-1;
      n = hist(data,i);
     end
  end

But I am making some mistakes. Thanks for any help.

I think this code based on your own will do it:

data = rand(100,1);
i = length(data);
n = hist(data, i);
min_number = 7;   % minimum no. in each bin
while any(n < min_number)
     i = i-1;
     [n bins] = hist(data,i);
end

figure
bar(bins,n)

(a). number of bin

nbin = length(bins);

(b). data in each bin

  • if you mean the number of counts per bin, that is returned directly by hist as n of course
  • if you mean, a pointer from each data entry to its corresponding bin, I would recommend modifying hist (make a copy as your own personal version) to return the output of histc which is run within hist , or calling histc after figuring out the edges of the histogram.

(c). bin size for each bin

hist uses equally sized bins, thus

binsize = bins(2)-bins(1)

(d). bin start & bin end for each bin

binedges = [bins'-binsize/2 bins'+binsize/2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM