1 ## Copyright (C) 2006, 2008 Bill Denney <bill@denney.ws>
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} {@var{y} =} squareform (@var{x})
18 ## @deftypefnx {Function File} {@var{y} =} squareform (@var{x}, @
20 ## @deftypefnx {Function File} {@var{y} =} squareform (@var{x}, @
22 ## Convert a vector from the pdist function into a square matrix or from
23 ## a square matrix back to the vector form.
25 ## The second argument is used to specify the output type in case there
26 ## is a single element.
30 ## Author: Bill Denney <bill@denney.ws>
32 function y = squareform (x, method)
37 if isscalar (x) || isvector (x)
42 error ("squareform: cannot deal with a nonsquare, nonvector \
46 method = lower (method);
48 if ! strcmp ({"tovector" "tomatrix"}, method)
49 error ("squareform: method must be either \"tovector\" or \
53 if strcmp ("tovector", method)
55 error ("squareform: x is not a square matrix");
59 y = zeros ((sx-1)*sx/2, 1);
62 newidx = idx + sx - i;
63 y(idx:newidx) = x(i:sx,i-1);
67 ## we're converting to a matrix
69 ## make sure that x is a column
72 ## the dimensions of y are the solution to the quadratic formula
74 ## length(x) = (sy-1)*(sy/2)
75 sy = (1 + sqrt (1+ 8*length (x)))/2;
79 y((sy-step+1):sy,i) = x(1:step);
87 ## make sure that it can go both directions automatically
88 %!assert(squareform(1:6), [0 1 2 3;1 0 4 5;2 4 0 6;3 5 6 0])
89 %!assert(squareform([0 1 2 3;1 0 4 5;2 4 0 6;3 5 6 0]), [1:6]')
91 ## make sure that the command arguments force the correct behavior
92 %!assert(squareform(1), [0 1;1 0])
93 %!assert(squareform(1, "tomatrix"), [0 1;1 0])
94 %!assert(squareform(1, "tovector"), zeros(0,1))