# HG changeset patch # User Rik # Date 1317841231 25200 # Node ID 04edb15d7966f4185caf14e2d5acf8610ae3fa98 # Parent 9f2e568123eabcd99f74589c3ae54bb1d916ec4c shift.m: Clean up code and add more tests * shift.m: Shift input validation to front of function. Add more tests for input validation. Tweak algorithm to avoid one unecessary calculation when the shift is 0 and add test for that. diff -r 9f2e568123ea -r 04edb15d7966 scripts/general/shift.m --- a/scripts/general/shift.m Wed Oct 05 11:43:05 2011 -0700 +++ b/scripts/general/shift.m Wed Oct 05 12:00:31 2011 -0700 @@ -37,7 +37,9 @@ print_usage (); endif - if (! (isscalar (b) && b == round (b))) + if (numel (x) < 1) + error ("shift: X must not be empty"); + elseif (! (isscalar (b) && b == fix (b))) error ("shift: B must be an integer"); endif @@ -45,7 +47,7 @@ sz = size (x); if (nargin == 3) - if (!(isscalar (dim) && dim == round (dim)) + if (!(isscalar (dim) && dim == fix (dim)) || !(1 <= dim && dim <= nd)) error ("shift: DIM must be an integer and a valid dimension"); endif @@ -54,24 +56,22 @@ (dim = find (sz > 1, 1)) || (dim = 1); endif - if (numel (x) < 1) - error ("shift: X must not be empty"); - endif - - d = sz (dim); + d = sz(dim); idx = repmat ({':'}, nd, 1); - if (b >= 0) + if (b > 0) b = rem (b, d); idx{dim} = [d-b+1:d, 1:d-b]; elseif (b < 0) b = rem (abs (b), d); idx{dim} = [b+1:d, 1:b]; endif + y = x(idx{:}); endfunction + %!test %! a = [1, 2, 3]; %! b = [4, 5, 6]; @@ -80,13 +80,19 @@ %! r = [a, b, c]; %! m = [a; b; c]; %! -%! assert((shift (r, 3) == [c, a, b] -%! && shift (r, -6) == [c, a, b] -%! && shift (r, -3) == [b, c, a] -%! && shift (m, 1) == [c; a; b] -%! && shift (m, -2) == [c; a; b])); +%! assert(shift (r, 0), r); +%! assert(shift (r, 3), [c, a, b]); +%! assert(shift (r, -6), [c, a, b]); +%! assert(shift (r, -3), [b, c, a]); +%! assert(shift (m, 1), [c; a; b]); +%! assert(shift (m, -2), [c; a; b]); -%!error shift (); +%% Test input validation +%!error shift () +%!error shift (1, 2, 3, 4) +%!error shift ([], 1) +%!error shift (ones(2), ones(2)) +%!error kurtosis (ones(2), 1.5) +%!error kurtosis (ones(2), 0) +%!error kurtosis (ones(2), 3) -%!error shift (1, 2, 3, 4); -