7017
|
1 ## Copyright (C) 2004, 2005, 2006, 2007 David Bateman |
4894
|
2 ## |
|
3 ## This file is part of Octave. |
|
4 ## |
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
7016
|
7 ## the Free Software Foundation; either version 3 of the License, or (at |
|
8 ## your option) any later version. |
4894
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
7016
|
16 ## along with Octave; see the file COPYING. If not, see |
|
17 ## <http://www.gnu.org/licenses/>. |
4894
|
18 |
|
19 ## -*- texinfo -*- |
6547
|
20 ## @deftypefn {Function File} {@var{y} =} circshift (@var{x}, @var{n}) |
4894
|
21 ## Circularly shifts the values of the array @var{x}. @var{n} must be |
|
22 ## a vector of integers no longer than the number of dimensions in |
|
23 ## @var{x}. The values of @var{n} can be either positive or negative, |
|
24 ## which determines the direction in which the values or @var{x} are |
|
25 ## shifted. If an element of @var{n} is zero, then the corresponding |
|
26 ## dimension of @var{x} will not be shifted. For example |
|
27 ## |
|
28 ## @example |
|
29 ## @group |
6671
|
30 ## x = [1, 2, 3; 4, 5, 6; 7, 8, 9]; |
4894
|
31 ## circshift (x, 1) |
|
32 ## @result{} 7, 8, 9 |
|
33 ## 1, 2, 3 |
|
34 ## 4, 5, 6 |
|
35 ## circshift (x, -2) |
|
36 ## @result{} 7, 8, 9 |
|
37 ## 1, 2, 3 |
|
38 ## 4, 5, 6 |
|
39 ## circshift (x, [0,1]) |
|
40 ## @result{} 3, 1, 2 |
|
41 ## 6, 4, 5 |
|
42 ## 9, 7, 8 |
|
43 ## @end group |
|
44 ## @end example |
5642
|
45 ## @seealso {permute, ipermute, shiftdim} |
4894
|
46 ## @end deftypefn |
|
47 |
4895
|
48 function y = circshift (x, n) |
4894
|
49 |
|
50 if (nargin == 2) |
|
51 nd = ndims (x); |
|
52 sz = size (x); |
|
53 |
4895
|
54 if (! isvector (n) && length (n) > nd) |
4894
|
55 error ("circshift: n must be a vector, no longer than the number of dimension in x"); |
|
56 endif |
|
57 |
4895
|
58 if (any (n != floor (n))) |
4894
|
59 error ("circshift: all values of n must be integers"); |
|
60 endif |
|
61 |
|
62 idx = cell (); |
4895
|
63 for i = 1:length (n); |
4894
|
64 nn = n(i); |
|
65 if (nn < 0) |
4895
|
66 while (sz(i) <= -nn) |
4894
|
67 nn = nn + sz(i); |
|
68 endwhile |
4895
|
69 idx{i} = [(1-nn):sz(i), 1:-nn]; |
4894
|
70 else |
|
71 while (sz(i) <= nn) |
|
72 nn = nn - sz(i); |
|
73 endwhile |
4895
|
74 idx{i} = [(sz(i)-nn+1):sz(i), 1:(sz(i)-nn)]; |
4894
|
75 endif |
|
76 endfor |
|
77 for i = (length(n) + 1) : nd |
|
78 idx{i} = 1:sz(i); |
|
79 endfor |
4895
|
80 y = x(idx{:}); |
4894
|
81 else |
6046
|
82 print_usage (); |
4894
|
83 endif |
|
84 endfunction |