1## Copyright (C) 2014 Georgios Ouzounis <ouzounis_georgios@hotmail.com>
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 3 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; see the file COPYING. If not, see
15## <https://www.gnu.org/licenses/>.
16
17## -*- texinfo -*-
18## @deftypefn  {Function File} {[@var{out perm shifts}] =} shiftdata (@var{in})
19## @deftypefnx {Function File} {[@var{out perm shifts}] =} shiftdata (@var{in}, @var{dim})
20## Shift data @var{in} to permute the dimension @var{dim} to the first column.
21## @seealso{unshiftdata}
22## @end deftypefn
23
24function [out, perm, shifts] = shiftdata (in, dim)
25
26  if (nargin < 1 || nargin > 2)
27    print_usage ();
28  elseif (nargin == 1 || (nargin == 2 && isempty (dim)))
29    idx = find (size (in) - 1);
30    dim = idx(1);
31    shiftsflag = true;
32  else
33    shiftsflag = false;
34  endif
35
36  if (dim != fix (dim))
37    error ("shiftdata: DIM must be an integer");
38  endif
39
40  perm = [dim 1: (dim - 1) (dim + 1): (length (size (in)))];
41  out = permute (in, perm);
42
43  if (shiftsflag == true)
44    perm = [];
45    shifts = dim - 1;
46  else
47    shifts = [];
48  endif
49
50endfunction
51
52%!test
53%! X = [1 2 3; 4 5 6; 7 8 9];
54%! [Y, perm, shifts] = shiftdata (X, 2);
55%! assert (Y, [1 4 7; 2 5 8; 3 6 9]);
56%! assert (perm, [2 1]);
57
58%!test
59%! X = [27 42 11; 63 48 5; 67 74 93];
60%! X(:, :, 2) = [15 23 81; 34 60 28; 70 54 38];
61%! [Y, perm, shifts] = shiftdata(X, 2);
62%! T = [27 63 67; 42 48 74; 11 5 93];
63%! T(:, :, 2) = [15 34 70; 23 60 54; 81 28 38];
64%! assert(Y, T);
65%! assert(perm, [2 1 3]);
66
67%!test
68%! X = fix (rand (4, 4, 4, 4) * 100);
69%! [Y, perm, shifts] = shiftdata (X, 3);
70%! T = 0;
71%! for i = 1:3
72%!   for j = 1:3
73%!     for k = 1:2
74%!       for l = 1:2
75%!         T = [T Y(k, i, j, l) - X(i, j, k ,l)];
76%!       endfor
77%!     endfor
78%!   endfor
79%! endfor
80%! assert (T, zeros (size (T)));
81
82## Test input validation
83%!error shiftdata ()
84%!error shiftdata (1, 2, 3)
85%!error shiftdata (1, 2.5)
86