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} {} zagzig (@var{mtrx})
18 ## Returns zagzig walk-off of the elements of @var{mtrx}.
19 ## Essentially it walks the matrix in a Z-fashion.
25 ## then zagzag(mat) gives the output,
26 ## [1 4 2 3 5 7 8 6 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. One use of
29 ## zagzig the use with picking up DCT coefficients
30 ## like in the JPEG algorithm for compression.
32 ## An example of zagzig use:
35 ## mat = reshape(1:9,3,3);
37 ## ans =[1 4 2 3 5 7 8 6 9]
45 function rval = zagzig(mtrx)
47 if nargin != 1 #Checking arguments.
51 if issquare(mtrx) #Square matrix (quick case)
53 ##We create a matrix of the same size as mtrx where odd elements are
55 odd=kron(ones(n,n),eye(2))((1:n),(1:n));
57 ##We transpose even elements only.
58 mtrx = (mtrx.*odd)' + (mtrx.*(1-odd));
60 ##Now we mirror the matrix. The desired vector is now the
61 ##concatenation of the diagonals.
62 mtrx=mtrx(:,1+size(mtrx,2)-(1:size(mtrx,2)));
64 ##Picking out the diagonals.
67 rval=[rval diag(mtrx,i)'];
70 else #Not square (Slow cases)
72 mtrx=mtrx(:,1+size(mtrx,2)-(1:size(mtrx,2)));
74 ##Picking out the diagonals and reversing odd ones manually.
76 for i = n(2)-1:-1:1-n(1)
78 if floor(i/2)==i/2 ##Even?
79 rval=[rval new((1+length(new))-(1:length(new)))'];
87 %!assert(zagzig(reshape(1:9,3,3)),[1 4 2 3 5 7 8 6 9])