1 ## Copyright (C) 2006-2012 David Bateman and Marco Caliari
2 ## Copyright (C) 2009 VZLU Prague
4 ## This file is part of Octave.
6 ## Octave is free software; you can redistribute it and/or modify it
7 ## under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 3 of the License, or (at
9 ## your option) any later version.
11 ## Octave is distributed in the hope that it will be useful, but
12 ## WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ## General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with Octave; see the file COPYING. If not, see
18 ## <http://www.gnu.org/licenses/>.
21 ## @deftypefn {Function File} {@var{n} =} normest (@var{A})
22 ## @deftypefnx {Function File} {@var{n} =} normest (@var{A}, @var{tol})
23 ## @deftypefnx {Function File} {[@var{n}, @var{c}] =} normest (@dots{})
24 ## Estimate the 2-norm of the matrix @var{A} using a power series
25 ## analysis. This is typically used for large matrices, where the cost
26 ## of calculating @code{norm (@var{A})} is prohibitive and an approximation
27 ## to the 2-norm is acceptable.
29 ## @var{tol} is the tolerance to which the 2-norm is calculated. By default
30 ## @var{tol} is 1e-6. @var{c} returns the number of iterations needed for
31 ## @code{normest} to converge.
34 function [n, c] = normest (A, tol = 1e-6)
36 if (nargin != 1 && nargin != 2)
40 if (! (isnumeric (A) && ndims (A) == 2))
41 error ("normest: A must be a numeric 2-D matrix");
44 if (! (isscalar (tol) && isreal (tol)))
45 error ("normest: TOL must be a real scalar");
52 tol = max (tol, eps (class (A)));
53 ## Set random number generator to depend on target matrix
55 rand ("state", trace (A));
57 ## Randomize y to avoid bad guesses for important matrices.
73 until (abs (n - n0) <= tol * n)
75 rand ("state", v); # restore state of random number generator
79 %! A = toeplitz ([-2,1,0,0]);
80 %! assert (normest(A), norm(A), 1e-6);
84 %! assert (normest(A), norm(A), 1e-6);
86 %% Test input validation
88 %!error normest (1, 2, 3)
89 %!error normest ([true true])
90 %!error normest (ones (3,3,3))
91 %!error normest (1, [1, 2])
92 %!error normest (1, 1+1i)