summaryrefslogtreecommitdiff
path: root/inst/arrays/@stk_dataframe/apply.m
blob: a3e303e50887633afb379e0d50f9f581a77df32f (plain)
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
% APPLY maps a function to the rows or columns of a dataframe.

% Copyright Notice
%
%    Copyright (C) 2015 CentraleSupelec
%    Copyright (C) 2013 SUPELEC
%
%    Author:  Julien Bect  <julien.bect@centralesupelec.fr>

% Copying Permission Statement
%
%    This file is part of
%
%            STK: a Small (Matlab/Octave) Toolbox for Kriging
%               (https://github.com/stk-kriging/stk/)
%
%    STK is free software: you can redistribute it and/or modify it under
%    the terms of the GNU General Public License as published by the Free
%    Software Foundation,  either version 3  of the License, or  (at your
%    option) any later version.
%
%    STK is distributed  in the hope that it will  be useful, but WITHOUT
%    ANY WARRANTY;  without even the implied  warranty of MERCHANTABILITY
%    or FITNESS  FOR A  PARTICULAR PURPOSE.  See  the GNU  General Public
%    License for more details.
%
%    You should  have received a copy  of the GNU  General Public License
%    along with STK.  If not, see <http://www.gnu.org/licenses/>.

function varargout = apply (x, dim, F, u)

if nargin == 4
    uu = {u};
else
    uu = {};
end

varargout = cell (1, max (1, nargout));

if dim == 1
    % act along columns
    [varargout{:}] = feval (F, x.data, uu{:}, 1);
else
    if dim ~= 2,
        stk_error ('Incorrect dimension specifier', 'IncorrectDimSpec');
    else
        % act along rows (less usual)
        [varargout{:}] = feval (F, x.data, uu{:}, 2);
    end
end

end % function

%!shared x, t, u
%! t = rand (3, 2);
%! x = stk_dataframe (t);

%!test u = apply (x, 1, @sum);
%!assert (isequal (u, sum (t, 1)))
%!test u = apply (x, 2, @sum);
%!assert (isequal (u, sum (t, 2)))
%!error u = apply (x, 3, @sum);

%!test u = apply (x, 1, @min, []);
%!assert (isequal (u, min (t, [], 1)))
%!test u = apply (x, 2, @min, []);
%!assert (isequal (u, min (t, [], 2)))
%!error u = apply (x, 3, @min, []);

%!test
%! t = [1; 3; 2];
%! x = stk_dataframe (t);
%! [M, k] = apply (x, 1, @max, []);
%! assert ((M == 3) && (k == 2));