7017
|
1 ## Copyright (C) 2004, 2005, 2007 David Bateman & Andy Adler |
5164
|
2 ## |
7016
|
3 ## This file is part of Octave. |
5164
|
4 ## |
7016
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
|
7 ## the Free Software Foundation; either version 3 of the License, or (at |
|
8 ## your option) any later version. |
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
5164
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
7016
|
16 ## along with Octave; see the file COPYING. If not, see |
|
17 ## <http://www.gnu.org/licenses/>. |
5164
|
18 |
|
19 ## -*- texinfo -*- |
|
20 ## @deftypefn {Function File} {@var{y} =} speye (@var{m}) |
|
21 ## @deftypefnx {Function File} {@var{y} =} speye (@var{m}, @var{n}) |
|
22 ## @deftypefnx {Function File} {@var{y} =} speye (@var{sz}) |
|
23 ## Returns a sparse identity matrix. This is significantly more |
|
24 ## efficient than @code{sparse (eye (@var{m}))} as the full matrix |
|
25 ## is not constructed. |
|
26 ## |
|
27 ## Called with a single argument a square matrix of size @var{m} by |
|
28 ## @var{m} is created. Otherwise a matrix of @var{m} by @var{n} is |
|
29 ## created. If called with a single vector argument, this argument |
|
30 ## is taken to be the size of the matrix to create. |
|
31 ## @end deftypefn |
|
32 |
6498
|
33 function s = speye (m, n) |
5164
|
34 if (nargin == 1) |
|
35 if (isvector (m) && length(m) == 2) |
|
36 n = m(2); |
|
37 m = m(1); |
|
38 elseif (isscalar (m)) |
|
39 n = m; |
|
40 else |
|
41 error ("speye: invalid matrix dimension"); |
|
42 endif |
|
43 else |
6498
|
44 if (! isscalar (m) || ! isscalar (n)) |
5164
|
45 error ("speye: invalid matrix dimension"); |
|
46 endif |
|
47 endif |
|
48 |
6498
|
49 lo = min ([m, n]); |
|
50 s = sparse (1:lo, 1:lo, 1, m, n); |
5164
|
51 endfunction |
|
52 |
|
53 %!assert(issparse(speye(4))) |
|
54 %!assert(speye(4),sparse(1:4,1:4,1)) |
|
55 %!assert(speye(2,4),sparse(1:2,1:2,1,2,4)) |
|
56 %!assert(speye(4,2),sparse(1:2,1:2,1,4,2)) |
|
57 %!assert(speye([4,2]),sparse(1:2,1:2,1,4,2)) |