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