-
Notifications
You must be signed in to change notification settings - Fork 10
/
weightedhistc.m
73 lines (63 loc) · 2.1 KB
/
weightedhistc.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
% WEIGHTEDHISTC Weighted histogram count
%
% This function provides a basic equivalent to MATLAB's HISTC function for
% weighted data.
%
% Usage: h = weightedhistc(vals, weights, edges)
%
% Arguments:
% vals - vector of values.
% weights - vector of weights associated with each element in vals. vals
% and weights must be vectors of the same length.
% edges - vector of bin boundaries to be used in the weighted histogram.
%
% Returns:
% h - The weighted histogram
% h(k) will count the weighted value vals(i)
% if edges(k) <= vals(i) < edges(k+1).
% The last bin will count any values of vals that match
% edges(end). Values outside the values in edges are not counted.
%
% Use bar(edges,h) to display histogram
%
% See also: HISTC
% Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% November 2010
%
% EDITED on 6/3/11 by W. Cox to add "left" and "right" methods for chosing
% the beginning/ending bin. "left" sets the first bin to be located exactly
% at the first edge. "right" sets the last bin to be located at exactly at
% the last edge
function h = weightedhistc(vals, weights, edges, side)
if ~isvector(vals) || ~isvector(weights) || length(vals)~=length(weights)
error('vals and weights must be vectors of the same size');
end
Nedge = length(edges);
h = zeros(size(edges));
if strcmp(side,'left')
ind = find(vals == edges(1));
if ~isempty(ind)
h(1) = sum(weights(ind));
end
for n = 1:Nedge-1
ind = find(vals > edges(n) & vals <= edges(n+1));
if ~isempty(ind)
h(n+1) = sum(weights(ind));
end
end
else
for n = 1:Nedge-1
ind = find(vals >= edges(n) & vals < edges(n+1));
if ~isempty(ind)
h(n) = sum(weights(ind));
end
end
ind = find(vals == edges(end));
if ~isempty(ind)
h(Nedge) = sum(weights(ind));
end
end