1########################################################################
2##
3## Copyright (C) 2004-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  {} {@var{s} =} speye (@var{m}, @var{n})
28## @deftypefnx {} {@var{s} =} speye (@var{m})
29## @deftypefnx {} {@var{s} =} speye (@var{sz})
30## Return a sparse identity matrix of size @var{m}x@var{n}.
31##
32## The implementation is significantly more efficient than
33## @code{sparse (eye (@var{m}))} as the full matrix is not constructed.
34##
35## Called with a single argument a square matrix of size
36## @var{m}-by-@var{m} is created.  If called with a single vector argument
37## @var{sz}, this argument is taken to be the size of the matrix to create.
38## @seealso{sparse, spdiags, eye}
39## @end deftypefn
40
41function s = speye (m, n)
42
43  if (nargin == 1)
44    if (isvector (m) && length (m) == 2)
45      n = m(2);
46      m = m(1);
47    elseif (isscalar (m))
48      n = m;
49    else
50      error ("speye: invalid matrix dimension");
51    endif
52  else
53    if (! isscalar (m) || ! isscalar (n))
54      error ("speye: invalid matrix dimension");
55    endif
56  endif
57
58  lo = min ([m, n]);
59  s = sparse (1:lo, 1:lo, 1, m, n);
60
61endfunction
62
63
64%!assert (issparse (speye (4)))
65%!assert (speye (4), sparse (1:4,1:4,1))
66%!assert (speye (2,4), sparse (1:2,1:2,1,2,4))
67%!assert (speye (4,2), sparse (1:2,1:2,1,4,2))
68%!assert (speye ([4,2]), sparse (1:2,1:2,1,4,2))
69