Mercurial > hg > octave-nkf
diff scripts/general/circshift.m @ 7614:52f90c7adac6
Avoid infinite loop in circshift for infinite matrices
author | David Bateman <dbateman@free.fr> |
---|---|
date | Thu, 20 Mar 2008 11:03:48 -0400 |
parents | a1dbe9d80eee |
children | eb63fbe60fab |
line wrap: on
line diff
--- a/scripts/general/circshift.m +++ b/scripts/general/circshift.m @@ -48,37 +48,49 @@ function y = circshift (x, n) if (nargin == 2) - nd = ndims (x); - sz = size (x); + if (isempty (x)) + y = x; + else + nd = ndims (x); + sz = size (x); - if (! isvector (n) && length (n) > nd) - error ("circshift: n must be a vector, no longer than the number of dimension in x"); - endif + if (! isvector (n) && length (n) > nd) + error ("circshift: n must be a vector, no longer than the number of dimension in x"); + endif - if (any (n != floor (n))) - error ("circshift: all values of n must be integers"); - endif + if (any (n != floor (n))) + error ("circshift: all values of n must be integers"); + endif - idx = cell (); - for i = 1:length (n); - nn = n(i); - if (nn < 0) - while (sz(i) <= -nn) - nn = nn + sz(i); - endwhile - idx{i} = [(1-nn):sz(i), 1:-nn]; - else - while (sz(i) <= nn) - nn = nn - sz(i); - endwhile - idx{i} = [(sz(i)-nn+1):sz(i), 1:(sz(i)-nn)]; - endif - endfor - for i = (length(n) + 1) : nd - idx{i} = 1:sz(i); - endfor - y = x(idx{:}); + idx = cell (); + for i = 1:length (n); + nn = n(i); + if (nn < 0) + while (sz(i) <= -nn) + nn = nn + sz(i); + endwhile + idx{i} = [(1-nn):sz(i), 1:-nn]; + else + while (sz(i) <= nn) + nn = nn - sz(i); + endwhile + idx{i} = [(sz(i)-nn+1):sz(i), 1:(sz(i)-nn)]; + endif + endfor + for i = (length(n) + 1) : nd + idx{i} = 1:sz(i); + endfor + y = x(idx{:}); + endif else print_usage (); endif endfunction + +%!shared x +%! x = [1, 2, 3; 4, 5, 6; 7, 8, 9]; + +%!assert (circshift (x, 1), [7, 8, 9; 1, 2, 3; 4, 5, 6]) +%!assert (circshift (x, -2), [7, 8, 9; 1, 2, 3; 4, 5, 6]) +%!assert (circshift (x, [0, 1]), [3, 1, 2; 6, 4, 5; 9, 7, 8]); +%!assert (circshift ([],1), [])