-
Notifications
You must be signed in to change notification settings - Fork 1
/
nanzscore.m
49 lines (43 loc) · 1.63 KB
/
nanzscore.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
function [z,mu,sigma] = zscore(x,flag,dim)
%ZSCORE Standardized z score.
% Z = ZSCORE(X) returns a centered, scaled version of X, the same size as X.
% For vector input X, Z is the vector of z-scores (X-MEAN(X)) ./ STD(X). For
% matrix X, z-scores are computed using the mean and standard deviation
% along each column of X. For higher-dimensional arrays, z-scores are
% computed using the mean and standard deviation along the first
% non-singleton dimension.
%
% The columns of Z have sample mean zero and sample standard deviation one
% (unless a column of X is constant, in which case that column of Z is
% constant at 0).
%
% [Z,MU,SIGMA] = ZSCORE(X) also returns MEAN(X) in MU and STD(X) in SIGMA.
%
% [...] = ZSCORE(X,1) normalizes X using STD(X,1), i.e., by computing the
% standard deviation(s) using N rather than N-1, where N is the length of
% the dimension along which ZSCORE works. ZSCORE(X,0) is the same as
% ZSCORE(X).
%
% [...] = ZSCORE(X,FLAG,DIM) standardizes X by working along the dimension
% DIM of X. Pass in FLAG==0 to use the default normalization by N-1, or 1
% to use N.
%
% See also MEAN, STD.
% Copyright 1993-2006 The MathWorks, Inc.
% [] is a special case for std and mean, just handle it out here.
if isequal(x,[]), z = []; return; end
if nargin < 2
flag = 0;
end
if nargin < 3
% Figure out which dimension to work along.
dim = find(size(x) ~= 1, 1);
if isempty(dim), dim = 1; end
end
% Compute X's mean and sd, and standardize it
mu = nanmean(x,dim);
sigma = nanstd(x,flag,dim);
sigma0 = sigma;
sigma0(sigma0==0) = 1;
z = bsxfun(@minus,x, mu);
z = bsxfun(@rdivide, z, sigma0);