histwc is a utility to construct weighted histogram. Given
number of bins, values and corresponding weights, there are
two functions produces identical outputs: a vector of histogram
frequencies and intervals. Functions generate a vector of
cumulative weights for data histogram. Equal number of bins
will be considered using minimum and maximum values of the data.
Weights will be summed in the given bin. These two vectors can
be used to plot the weighted histogram. One of the function is
vectorized, but not necessarily faster.
%vv = [1.0 1.0 2.0 5.0 3.0 4.0 1.0 5.0 3.0 1.0]; % values
%ww = [0.1 0.1 0.05 0.05 0.2 0.05 0.05 0.1 0.1 0.2]; % weights
%nbins = 5;
%[histw, intervals] = histwc(vv, ww, nbins);
% Example Visualise:
% bar(intervals, histw)
Thank you very much, it was really helpful.
Thank you Brent. One otherway to make it even faster is to use C++ via MEX.
There is a much faster option available (I am using R2014a) using accumarray. For my applications the code below was 100 times faster.
function [histw histv] = histwv(v, w, min, max, bins)
%vv - values
%ww - weights
%minV - minimum value
%maxV - max value
%bins - number of bins (inclusive)
%histw - wieghted histogram
%histv (optional) - histogram of values
delta = (max-min)/(bins-1);
subs = round((v-min)/delta)+1;
histv = accumarray(subs,1,[bins,1]);
histw = accumarray(subs,w,[bins,1]);
Hi! Just a comment: If you want a weighted histogram in more than one dimension, you can use the submission histcn in file exchange. Just use the option histcn(...,'AccumData', weights); The result will not be 100% the same as the one obtained with this function, since the bin edges are calculated differently.
It works perfectly to me. Thank you!