1 ## Copyright (C) 2006 Fredrik Bulow <fredrik.bulow@gmail.com>
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
17 ## @deftypefn {Function File} {} zigzag (@var{mtrx})
18 ## Returns zigzag walk-off of the elements of @var{mtrx}.
19 ## Essentially it walks the matrix in a Z-fashion.
25 ## then zigzag(mat) gives the output,
26 ## [1 2 4 7 5 3 6 8 9], by walking as
27 ## shown in the figure from pt 1 in that order of output.
28 ## The argument @var{mtrx} should be a MxN matrix
30 ## An example of zagzig use:
33 ## mat = reshape(1:9,3,3);
35 ## ans =[1 2 4 7 5 3 6 8 9]
43 function rval = zigzag(mtrx)
49 if(issquare(mtrx)) #Square matrix (quick case)
51 ##We create a matrix of the same size as mtrx where odd elements are
53 odd=kron(ones(ceil(n/2)),eye(2))((1:n(1)),(1:n(2)));
55 ##We transpose even elements only.
56 mtrx = mtrx.*odd + (mtrx.*(1-odd))';
58 ##Now we mirror the matrix. The desired vector is now the
59 ##concatenation of the diagonals.
60 mtrx=mtrx(:,1+size(mtrx,2)-(1:size(mtrx,2)));
62 ##Picking out the diagonals.
64 for i = n(2)-1:-1:1-n(1)
65 rval=[rval diag(mtrx,i)'];
68 else #Not square (Slow cases)
69 mtrx=mtrx(:,1+size(mtrx,2)-(1:size(mtrx,2)));
71 ##Picking out the diagonals and reversing odd ones manually.
73 for i = n(2)-1:-1:1-n(1)
75 if(floor(i/2)==i/2) ##Even?
78 rval=[rval new((1+length(new))-(1:length(new)))'];
84 %!assert(zigzag(reshape(1:9,3,3)),[1 2 4 7 5 3 6 8 9])