This repository has been archived by the owner on Feb 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
wmean.m
51 lines (45 loc) · 1.38 KB
/
wmean.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
function y = wmean(x,w,dim)
%WMEAN Weighted Average or mean value.
% For vectors, WMEAN(X,W) is the weighted mean value of the elements in X
% using non-negative weights W. For matrices, WMEAN(X,W) is a row vector
% containing the weighted mean value of each column. For N-D arrays,
% WMEAN(X,W) is the weighted mean value of the elements along the first
% non-singleton dimension of X.
%
% Each element of X requires a corresponding weight, and hence the size
% of W must match that of X.
%
% WMEAN(X,W,DIM) takes the weighted mean along the dimension DIM of X.
%
% Class support for inputs X and W:
% float: double, single
%
% Example:
% x = rand(5,2);
% w = rand(5,2);
% wmean(x,w)
%
% BSD licence from Matlab site
if nargin<2
error('Not enough input arguments.');
end
% Check that dimensions of X match those of W.
if(~isequal(size(x), size(w)))
error('Inputs x and w must be the same size.');
end
% Check that all of W are non-negative.
if (any(w(:)<0))
error('All weights, W, must be non-negative.');
end
% Check that there is at least one non-zero weight.
if (all(w(:)==0))
warning('TASBE:WeightedMean','At least one weight must be non-zero.');
y = nan;
return;
end
if nargin==2,
% Determine which dimension SUM will use
dim = min(find(size(x)~=1));
if isempty(dim), dim = 1; end
end
y = sum(w.*x,dim)./sum(w,dim);