]> Creatis software - CreaPhase.git/blob - octave_packages/miscellaneous-1.1.0/zigzag.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / miscellaneous-1.1.0 / zigzag.m
1 ## Copyright (C) 2006 Fredrik Bulow <fredrik.bulow@gmail.com>
2 ##
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
6 ## version.
7 ##
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
11 ## details.
12 ##
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/>.
15
16 ## -*- texinfo -*-
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.
20 ##  
21 ## mat = 
22 ##   1   4   7
23 ##   2   5   8
24 ##   3   6   9
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 
29 ##
30 ## An example of zagzig use:
31 ## @example
32 ## @group
33 ## mat = reshape(1:9,3,3);
34 ## zigzag(mat)
35 ## ans =[1   2   4   7   5   3   6   8   9]
36 ##
37 ## @end group
38 ## @end example
39 ##
40 ## @end deftypefn
41 ## @seealso{zagzig}
42
43 function rval = zigzag(mtrx)
44   if nargin != 1
45     print_usage;
46   endif
47   n=size(mtrx);
48   
49   if(issquare(mtrx)) #Square matrix (quick case)
50
51     ##We create a matrix of the same size as mtrx where odd elements are
52     ##1, others 0.
53     odd=kron(ones(ceil(n/2)),eye(2))((1:n(1)),(1:n(2)));
54
55     ##We transpose even elements only.
56     mtrx = mtrx.*odd + (mtrx.*(1-odd))';
57
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)));
61
62     ##Picking out the diagonals.
63     rval  = [];
64     for i = n(2)-1:-1:1-n(1)
65       rval=[rval diag(mtrx,i)'];
66     endfor
67
68   else #Not square (Slow cases)
69     mtrx=mtrx(:,1+size(mtrx,2)-(1:size(mtrx,2)));
70
71     ##Picking out the diagonals and reversing odd ones manually.
72     rval  = [];
73     for i = n(2)-1:-1:1-n(1)
74       new = diag(mtrx,i);
75       if(floor(i/2)==i/2) ##Even?
76         rval=[rval new'];
77       else                ##Odd!
78         rval=[rval new((1+length(new))-(1:length(new)))'];
79       endif
80     endfor
81   endif
82 endfunction
83
84 %!assert(zigzag(reshape(1:9,3,3)),[1   2   4   7   5   3   6   8   9])