File Exchange

## Generate Weighted Histogram

version 1.0 (3.79 KB) by

histwc is a simple utility to construct weighted histogram.

4.66667
3 Ratings

Updated

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.

Example:
%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)

### Comments and Ratings (5)

Dominika Maslarova

### Dominika Maslarova (view profile)

Thank you very much, it was really helpful.

Mehmet Suzen

### Mehmet Suzen (view profile)

Thank you Brent. One otherway to make it even faster is to use C++ via MEX.

Brent

### Brent (view profile)

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)
%Inputs:
%vv - values
%ww - weights
%minV - minimum value
%maxV - max value
%bins - number of bins (inclusive)

%Outputs:
%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]);
end

Jdeen

### Jdeen (view profile)

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.

Chi-Fu

### Chi-Fu (view profile)

It works perfectly to me. Thank you!

##### MATLAB Release
MATLAB 7.14 (R2012a)
##### Acknowledgements

Inspired: histwv(v, w, min, max, bins)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

Play today