245
|
1 # Copyright (C) 1993 John W. Eaton |
|
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 the |
|
7 # Free Software Foundation; either version 2, or (at your option) any |
|
8 # later version. |
|
9 # |
|
10 # Octave is distributed in the hope that it will be useful, but WITHOUT |
|
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
12 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
13 # for more details. |
|
14 # |
|
15 # You should have received a copy of the GNU General Public License |
|
16 # along with Octave; see the file COPYING. If not, write to the Free |
|
17 # Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. |
|
18 |
4
|
19 function retval = norm (x, p) |
|
20 |
|
21 # usage: norm (x, p) |
|
22 # |
|
23 # Compute the p-norm of x. |
|
24 # |
|
25 # If x is a matrix: |
|
26 # |
|
27 # value of p norm returns |
|
28 # ---------- ------------ |
|
29 # 1 1-norm, the largest column sum of x |
|
30 # 2 largest singular value of x |
|
31 # Inf infinity norm, the largest row sum of x |
|
32 # "fro" Frobenius norm of x, sqrt (sum (diag (x' * x))) |
|
33 # |
|
34 # If x is a vector or a scalar: |
|
35 # |
|
36 # value of p norm returns |
|
37 # ---------- ------------ |
|
38 # Inf max (abs (x)) |
|
39 # -Inf min (abs (x)) |
|
40 # other p-norm of x, sum (abs (x) .^ p) ^ (1/p) |
|
41 # |
|
42 # If the second argument is missing, p = 2 is assumed. |
|
43 # |
|
44 # See also: cond, svd |
|
45 |
|
46 if (nargin < 1 || nargin > 2) |
|
47 error ("usage: norm (x [, p])") |
|
48 endif |
|
49 |
|
50 # Do we have a vector or matrix as the first argument? |
|
51 |
|
52 if (rows (x) == 1 || columns (x) == 1) |
|
53 |
|
54 if (nargin == 2) |
|
55 if (isstr (p)) |
|
56 if (strcmp (p, "fro")) |
|
57 retval = sqrt (sum (diag (x' * x))); |
|
58 else |
|
59 error ("norm: unrecognized norm"); |
|
60 endif |
|
61 else |
|
62 if (p == Inf) |
|
63 retval = max (abs (x)); |
|
64 elseif (p == -Inf) |
|
65 retval = min (abs (x)); |
|
66 else |
|
67 retval = sum (abs (x) .^ p) ^ (1/p); |
|
68 endif |
|
69 endif |
|
70 elseif (nargin == 1) |
|
71 retval = sum (abs (x) .^ 2) ^ 0.5; |
|
72 endif |
|
73 |
|
74 else |
|
75 |
|
76 if (nargin == 2) |
|
77 if (isstr (p)) |
|
78 if (strcmp (p, "fro")) |
|
79 retval = sqrt (sum (diag (x' * x))); |
|
80 else |
|
81 error ("norm: unrecognized norm"); |
|
82 endif |
|
83 else |
|
84 if (p == 1) |
|
85 retval = max (sum (abs (real (x)) + abs (imag (x)))); |
|
86 elseif (p == 2) |
|
87 s = svd (x); |
|
88 retval = s (1); |
|
89 elseif (p == Inf) |
|
90 xp = x'; |
|
91 retval = max (sum (abs (real (xp)) + abs (imag (xp)))); |
|
92 endif |
|
93 endif |
|
94 elseif (nargin == 1) |
|
95 s = svd (x); |
|
96 retval = s (1); |
|
97 endif |
|
98 |
|
99 endif |
|
100 |
|
101 endfunction |