changeset 11708:7a5439d343da release-3-0-x

Avoid infinite loop in circshift for infinite matrices
author David Bateman <dbateman@free.fr>
date Thu, 20 Mar 2008 12:13:03 -0400
parents 017b7c79bd3c
children ac34316ad003
files scripts/ChangeLog scripts/general/circshift.m
diffstat 2 files changed, 41 insertions(+), 27 deletions(-) [+]
line wrap: on
line diff
--- a/scripts/ChangeLog
+++ b/scripts/ChangeLog
@@ -2,6 +2,8 @@
 
 	* general/rotdim.m: Ensure k is an integer scale.
  
+	* general/circshift.m: If matrix is empty fast return.
+
 2008-03-19  Emil Lucretiu  <emil@la.mine.nu>
 
 	* signal/sinetone.m: Ensure integral number of samples.
--- 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), [])