1## Copyright (C) 2007 Lukasz Komsta, http://www.komsta.net/
2##
3## This program is free software; you can redistribute it and/or modify
4## it under the terms of the GNU General Public License as published by
5## the Free Software Foundation; either version 2 of the License, or
6## (at your option) any later version.
7##
8## This program is distributed in the hope that it will be useful,
9## but WITHOUT ANY WARRANTY; without even the implied warranty of
10## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11## GNU General Public License for more details.
12##
13## You should have received a copy of the GNU General Public License
14## along with this program; If not, see <http://www.gnu.org/licenses/>.
15
16## Remove the value(s) most differing from the mean
17##
18## Description:
19##
20##      This function can remove the outliers or replace by sample mean or median.
21##
22## Usage:
23##
24##      [res] = rmoutlier(x,fill,median,opposite)
25##
26## Arguments:
27##
28##        x: a dataset, most frequently a vector. If argument is a
29##           matrix, each column is treated as independent dataset.
30##
31##     fill: If set to 1 (default 0), the median or mean is placed instead of
32##           outlier. Otherwise,  the outlier(s) is/are simply removed.
33##
34##   median: If set to 1 (default 0), median is used instead of mean in outlier
35##           replacement.
36##
37## opposite: if set to 1 (default 0), replaces opposite value (if largest value has
38##           maximum difference from the mean, it replaces smallest and vice
39##           versa)
40##
41## Value:
42##
43##      A dataset of the same type as argument, with outlier(s) removed or
44##      replaced by appropriate means or medians.
45##
46## Author(s):
47##
48##      Lukasz Komsta, ported from R package "outliers".
49##	See R News, 6(2):10-13, May 2006
50##
51##
52
53
54function [res] = rmoutlier(x,fill,median,opposite)
55
56	if nargin<4
57		opposite=0;
58	end
59	if nargin<3
60		median=0;
61	end
62	if nargin<2
63		fill=0;
64	end
65
66if ~isvector(x) & ismatrix(x)
67	res = [];
68	for i=1:columns(x)
69		rr = rmoutlier(x(:,i),fill,median,opposite);
70		res = [res rr];
71	end
72
73elseif isvector(x)
74	wo = x;
75	ou = find(x == outlier(x,opposite));
76		for i=1:length(ou)
77			wo(ou(i)) = [];
78		end
79
80        if ~fill
81		res = wo;
82	else
83       		res = x;
84 		for i=1:length(ou)
85			if median
86			res(ou(i)) = median(wo);
87			else
88			res(ou(i)) = mean(wo);
89			end
90		end
91  	end
92end
93end
94