# HG changeset patch # User Rik # Date 1307466251 25200 # Node ID 6835bc816ef2034aa92e0e70dfdd8ec91a08a531 # Parent 65b7ce254ba3057c1dff0f550b27e8cf783d3fa4 shiftdim.m: Use common idiom for finding first non-singleton dimension. Add tests for function. * shiftdim.m: Use common idiom for finding first non-singleton dimension. Add functional tests to .m file. diff -r 65b7ce254ba3 -r 6835bc816ef2 scripts/general/shiftdim.m --- a/scripts/general/shiftdim.m Thu Jun 02 16:31:13 2011 +0200 +++ b/scripts/general/shiftdim.m Tue Jun 07 10:04:11 2011 -0700 @@ -57,14 +57,9 @@ orig_dims = size (x); if (nargin == 1) - ## Find the first singleton dimension. - n = 0; - while (n < nd && orig_dims(n+1) == 1) - n++; - endwhile - endif - - if (! isscalar (n) || floor (n) != n) + ## Find the first non-singleton dimension. + (n = find (orig_dims != 1, 1) - 1) || (n = nd); + elseif (! (isscalar (n) && n == fix (n))) error ("shiftdim: N must be a scalar integer"); endif @@ -78,7 +73,7 @@ elseif (n > 0) ## We need permute here instead of reshape to shift values in a ## compatible way. - y = permute (x, [n+1:ndims(x) 1:n]); + y = permute (x, [n+1:nd 1:n]); else y = x; endif @@ -86,3 +81,20 @@ ns = n; endfunction + + +%!test +%! x = rand (1, 1, 4, 2); +%! [y, ns] = shiftdim (x); +%! assert (size (y), [4 2]); +%! assert (ns, 2); +%! assert (shiftdim (y, -2), x); +%! assert (size (shiftdim (x, 2)), [4 2]); +%!assert (size (shiftdim (rand (0, 1, 2))), [0 1 2]); + +%% Test input validation +%!error(shiftdim ()); +%!error(shiftdim (1,2,3)); +%!error(shiftdim (1, ones (2))); +%!error(shiftdim (1, 1.5)); +