-
Notifications
You must be signed in to change notification settings - Fork 1
/
despikeRBR.m
89 lines (57 loc) · 2.03 KB
/
despikeRBR.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
function out = despikeRBR(in,vars,algorithm,np,replaceWith)
%
% usage:
%
% out = despikeRBR(in,vars,algorithm,np,replaceWith)
%
% where:
% in : structure of rbr data (ie output from rbrExtractVals.m)
% vars : cell array of strings describing which variables
% to filter
% algorithm : one of 'median' or 'mean'
% np : number of points in running mean/median
% replaceWith : How to treat the flagged values:
% : one of 'filtered', 'interp', or 'NaN'
% : 'filtered' - use filtered (mean/median) version
% : 'interp' - linear interpolation over flagged values
% : 'NaN' - replace flagged values with NaN
%
if ischar(vars),
vars = cellstr(vars);
end
out = in;
for j = 1:length(vars)
tvar = in.(vars{j});
switch algorithm
case 'median'
ftvar = medfilt1(tvar,np,'omitnan');
case 'mean'
fltr = boxcar(np)/sum(boxcar(np));fltr = fltr(:);
ftvar = tvar;
kk = isfinite(ftvar); % quick and dirty handling of NaNs
% (not great) should probably interp,
% filter, and then re-NaN
ftvar(kk) = filtfilt(fltr,1,tvar(kk));
end
% pick out the offenders
res = tvar - ftvar;
thresh = 4*nanstd(res);
jj = abs(res) >= thresh;
switch replaceWith
case 'filtered'
out.(vars{j}) = ftvar;
case 'interp'
out.(vars{j}) = interp1(in.mtime(~jj),tvar(~jj),in.mtime);
case 'NaN'
tvar(jj) = NaN;
out.(vars{j}) = tvar;
end
end
if numel(vars)>1,
vars = strjoin(vars,', ');
end
nlog = length(out.processingLog);
out.processingLog(nlog+1) = {['De-spiking applied to ' char(vars) ...
' with ' num2str(np) ' point ' algorithm ...
' algorithm. Bad values treated with ' ...
replaceWith '.']};