1########################################################################
2##
3## Copyright (C) 1995-2021 The Octave Project Developers
4##
5## See the file COPYRIGHT.md in the top-level directory of this
6## distribution or <https://octave.org/copyright/>.
7##
8## This file is part of Octave.
9##
10## Octave is free software: you can redistribute it and/or modify it
11## under the terms of the GNU General Public License as published by
12## the Free Software Foundation, either version 3 of the License, or
13## (at your option) any later version.
14##
15## Octave is distributed in the hope that it will be useful, but
16## WITHOUT ANY WARRANTY; without even the implied warranty of
17## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18## GNU General Public License for more details.
19##
20## You should have received a copy of the GNU General Public License
21## along with Octave; see the file COPYING.  If not, see
22## <https://www.gnu.org/licenses/>.
23##
24########################################################################
25
26## -*- texinfo -*-
27## @deftypefn {} {} vech (@var{x})
28## Return the vector obtained by eliminating all superdiagonal elements of
29## the square matrix @var{x} and stacking the result one column above the
30## other.
31##
32## This has uses in matrix calculus where the underlying matrix is symmetric
33## and it would be pointless to keep values above the main diagonal.
34## @seealso{vec}
35## @end deftypefn
36
37## See Magnus and Neudecker (1988), Matrix differential calculus with
38## applications in statistics and econometrics.
39
40## Author KH <Kurt.Hornik@wu-wien.ac.at>
41
42function v = vech (x)
43
44  if (nargin != 1)
45    print_usage ();
46  endif
47
48  if (! issquare (x))
49    error ("vech: X must be square");
50  endif
51
52  n = rows (x);
53  slices = cellslices (x(:), (1:n) + n*(0:n-1), n*(1:n));
54  v = vertcat (slices{:});
55
56endfunction
57
58
59%!assert (vech ([1, 2, 3; 4, 5, 6; 7, 8, 9]), [1; 4; 7; 5; 8; 9])
60
61%!error vech ()
62%!error vech (1, 2)
63