4894
|
1 ## Copyright (C) 2004 David Bateman |
|
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 |
|
7 ## the Free Software Foundation; either version 2, or (at your option) |
|
8 ## any later version. |
|
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 |
|
16 ## along with Octave; see the file COPYING. If not, write to the Free |
5307
|
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
|
18 ## 02110-1301, USA. |
4894
|
19 |
|
20 ## -*- texinfo -*- |
6547
|
21 ## @deftypefn {Function File} {@var{y} =} circshift (@var{x}, @var{n}) |
4894
|
22 ## Circularly shifts the values of the array @var{x}. @var{n} must be |
|
23 ## a vector of integers no longer than the number of dimensions in |
|
24 ## @var{x}. The values of @var{n} can be either positive or negative, |
|
25 ## which determines the direction in which the values or @var{x} are |
|
26 ## shifted. If an element of @var{n} is zero, then the corresponding |
|
27 ## dimension of @var{x} will not be shifted. For example |
|
28 ## |
|
29 ## @example |
|
30 ## @group |
6671
|
31 ## x = [1, 2, 3; 4, 5, 6; 7, 8, 9]; |
4894
|
32 ## circshift (x, 1) |
|
33 ## @result{} 7, 8, 9 |
|
34 ## 1, 2, 3 |
|
35 ## 4, 5, 6 |
|
36 ## circshift (x, -2) |
|
37 ## @result{} 7, 8, 9 |
|
38 ## 1, 2, 3 |
|
39 ## 4, 5, 6 |
|
40 ## circshift (x, [0,1]) |
|
41 ## @result{} 3, 1, 2 |
|
42 ## 6, 4, 5 |
|
43 ## 9, 7, 8 |
|
44 ## @end group |
|
45 ## @end example |
5642
|
46 ## @seealso {permute, ipermute, shiftdim} |
4894
|
47 ## @end deftypefn |
|
48 |
4895
|
49 function y = circshift (x, n) |
4894
|
50 |
|
51 if (nargin == 2) |
|
52 nd = ndims (x); |
|
53 sz = size (x); |
|
54 |
4895
|
55 if (! isvector (n) && length (n) > nd) |
4894
|
56 error ("circshift: n must be a vector, no longer than the number of dimension in x"); |
|
57 endif |
|
58 |
4895
|
59 if (any (n != floor (n))) |
4894
|
60 error ("circshift: all values of n must be integers"); |
|
61 endif |
|
62 |
|
63 idx = cell (); |
4895
|
64 for i = 1:length (n); |
4894
|
65 nn = n(i); |
|
66 if (nn < 0) |
4895
|
67 while (sz(i) <= -nn) |
4894
|
68 nn = nn + sz(i); |
|
69 endwhile |
4895
|
70 idx{i} = [(1-nn):sz(i), 1:-nn]; |
4894
|
71 else |
|
72 while (sz(i) <= nn) |
|
73 nn = nn - sz(i); |
|
74 endwhile |
4895
|
75 idx{i} = [(sz(i)-nn+1):sz(i), 1:(sz(i)-nn)]; |
4894
|
76 endif |
|
77 endfor |
|
78 for i = (length(n) + 1) : nd |
|
79 idx{i} = 1:sz(i); |
|
80 endfor |
4895
|
81 y = x(idx{:}); |
4894
|
82 else |
6046
|
83 print_usage (); |
4894
|
84 endif |
|
85 endfunction |