7017
|
1 ## Copyright (C) 2000, 2006, 2007 Paul Kienzle |
5827
|
2 ## |
|
3 ## This file is part of Octave. |
|
4 ## |
|
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 |
7016
|
7 ## the Free Software Foundation; either version 3 of the License, or (at |
|
8 ## your option) any later version. |
5827
|
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. |
|
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/>. |
5827
|
18 |
|
19 ## -*- texinfo -*- |
|
20 ## @deftypefn {Function File} {[@var{r}, @var{k}] =} rref (@var{a}, @var{tol}) |
|
21 ## |
|
22 ## Returns the reduced row echelon form of @var{a}. @var{tol} defaults |
|
23 ## to @code{eps * max (size (@var{a})) * norm (@var{a}, inf)}. |
|
24 ## |
|
25 ## Called with two return arguments, @var{k} returns the vector of |
|
26 ## "bound variables", which are those columns on which elimination |
|
27 ## has been performed. |
|
28 ## |
|
29 ## @end deftypefn |
|
30 |
|
31 ## Author: Paul Kienzle <pkienzle@users.sf.net> |
|
32 ## (based on a anonymous source from the public domain) |
|
33 |
|
34 function [A, k] = rref (A, tolerance) |
|
35 |
|
36 if (nargin < 1 || nargin > 2) |
|
37 print_usage (); |
|
38 endif |
|
39 |
|
40 if (ndims (A) > 2) |
|
41 error ("rref: expecting matrix argument"); |
|
42 endif |
|
43 |
|
44 [rows, cols] = size (A); |
|
45 |
|
46 if (nargin < 2) |
|
47 tolerance = eps * max (rows, cols) * norm (A, inf); |
|
48 endif |
|
49 |
|
50 used = zeros (1, cols); |
|
51 r = 1; |
|
52 for c = 1:cols |
|
53 ## Find the pivot row |
|
54 [m, pivot] = max (abs (A(r:rows,c))); |
|
55 pivot = r + pivot - 1; |
|
56 |
|
57 if (m <= tolerance) |
|
58 ## Skip column c, making sure the approximately zero terms are |
|
59 ## actually zero. |
|
60 A (r:rows, c) = zeros (rows-r+1, 1); |
|
61 else |
|
62 ## keep track of bound variables |
|
63 used (1, c) = 1; |
|
64 |
|
65 ## Swap current row and pivot row |
|
66 A ([pivot, r], c:cols) = A ([r, pivot], c:cols); |
|
67 |
|
68 ## Normalize pivot row |
|
69 A (r, c:cols) = A (r, c:cols) / A (r, c); |
|
70 |
|
71 ## Eliminate the current column |
|
72 ridx = [1:r-1, r+1:rows]; |
|
73 A (ridx, c:cols) = A (ridx, c:cols) - A (ridx, c) * A(r, c:cols); |
|
74 |
|
75 ## Check if done |
|
76 if (r++ == rows) |
|
77 break; |
|
78 endif |
|
79 endif |
|
80 endfor |
|
81 k = find (used); |
|
82 |
|
83 endfunction |