GNU Octave  8.1.0
A high-level interpreted language, primarily intended for numerical computations, mostly compatible with Matlab
inv.cc
Go to the documentation of this file.
1 ////////////////////////////////////////////////////////////////////////
2 //
3 // Copyright (C) 1996-2023 The Octave Project Developers
4 //
5 // See the file COPYRIGHT.md in the top-level directory of this
6 // distribution or <https://octave.org/copyright/>.
7 //
8 // This file is part of Octave.
9 //
10 // Octave is free software: you can redistribute it and/or modify it
11 // under the terms of the GNU General Public License as published by
12 // the Free Software Foundation, either version 3 of the License, or
13 // (at your option) any later version.
14 //
15 // Octave is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with Octave; see the file COPYING. If not, see
22 // <https://www.gnu.org/licenses/>.
23 //
24 ////////////////////////////////////////////////////////////////////////
25 
26 #if defined (HAVE_CONFIG_H)
27 # include "config.h"
28 #endif
29 
30 #include "defun.h"
31 #include "error.h"
32 #include "errwarn.h"
33 #include "ovl.h"
34 #include "ops.h"
35 #include "ov-re-diag.h"
36 #include "ov-cx-diag.h"
37 #include "ov-flt-re-diag.h"
38 #include "ov-flt-cx-diag.h"
39 #include "ov-perm.h"
40 
42 
43 DEFUN (inv, args, nargout,
44  doc: /* -*- texinfo -*-
45 @deftypefn {} {@var{x} =} inv (@var{A})
46 @deftypefnx {} {[@var{x}, @var{rcond}] =} inv (@var{A})
47 @deftypefnx {} {[@dots{}] =} inverse (@dots{})
48 Compute the inverse of the square matrix @var{A}.
49 
50 Return an estimate of the reciprocal condition number if requested,
51 otherwise warn of an ill-conditioned matrix if the reciprocal condition
52 number is small.
53 
54 In general it is best to avoid calculating the inverse of a matrix directly.
55 For example, it is both faster and more accurate to solve systems of
56 equations (@var{A}*@math{x} = @math{b}) with
57 @code{@var{y} = @var{A} \ @math{b}}, rather than
58 @code{@var{y} = inv (@var{A}) * @math{b}}.
59 
60 If called with a sparse matrix, then in general @var{x} will be a full
61 matrix requiring significantly more storage. Avoid forming the inverse of a
62 sparse matrix if possible.
63 
64 @code{inverse} is an alias and may be used identically in place of @code{inv}.
65 @seealso{ldivide, rdivide, pinv}
66 @end deftypefn */)
67 {
68  if (args.length () != 1)
69  print_usage ();
70 
71  octave_value arg = args(0);
72 
73  if (! arg.isnumeric ())
74  err_wrong_type_arg ("inv", arg);
75 
76  if (arg.isempty ())
77  return ovl (Matrix ());
78 
79  if (arg.rows () != arg.columns ())
80  err_square_matrix_required ("inv", "A");
81 
82  octave_value result;
83  octave_idx_type info = 0;
84  double rcond = 0.0;
85  float frcond = 0.0;
86  bool isfloat = arg.is_single_type ();
87 
88  if (arg.is_diag_matrix ())
89  {
90  rcond = 1.0;
91  frcond = 1.0f;
92  if (arg.iscomplex ())
93  {
94  if (isfloat)
95  {
96  result = arg.float_complex_diag_matrix_value ().inverse (info);
97  if (info == -1)
98  frcond = 0.0f;
99  else if (nargout > 1)
100  frcond = arg.float_complex_diag_matrix_value ().rcond ();
101  }
102  else
103  {
104  result = arg.complex_diag_matrix_value ().inverse (info);
105  if (info == -1)
106  rcond = 0.0;
107  else if (nargout > 1)
108  rcond = arg.complex_diag_matrix_value ().rcond ();
109  }
110  }
111  else
112  {
113  if (isfloat)
114  {
115  result = arg.float_diag_matrix_value ().inverse (info);
116  if (info == -1)
117  frcond = 0.0f;
118  else if (nargout > 1)
119  frcond = arg.float_diag_matrix_value ().rcond ();
120  }
121  else
122  {
123  result = arg.diag_matrix_value ().inverse (info);
124  if (info == -1)
125  rcond = 0.0;
126  else if (nargout > 1)
127  rcond = arg.diag_matrix_value ().rcond ();
128  }
129  }
130  }
131  else if (arg.is_perm_matrix ())
132  {
133  info = 0;
134  rcond = 1.0;
135  result = arg.perm_matrix_value ().inverse ();
136  }
137  else if (isfloat)
138  {
139  if (arg.isreal ())
140  {
142 
143  MatrixType mattyp = args(0).matrix_type ();
144  result = m.inverse (mattyp, info, frcond, true, true);
145  args(0).matrix_type (mattyp);
146  }
147  else if (arg.iscomplex ())
148  {
150 
151  MatrixType mattyp = args(0).matrix_type ();
152  result = m.inverse (mattyp, info, frcond, true, true);
153  args(0).matrix_type (mattyp);
154  }
155  }
156  else
157  {
158  if (arg.isreal ())
159  {
160  if (arg.issparse ())
161  {
163 
164  MatrixType mattyp = args(0).matrix_type ();
165  result = m.inverse (mattyp, info, rcond, true, true);
166  args(0).matrix_type (mattyp);
167  }
168  else
169  {
170  Matrix m = arg.matrix_value ();
171 
172  MatrixType mattyp = args(0).matrix_type ();
173  result = m.inverse (mattyp, info, rcond, true, true);
174  args(0).matrix_type (mattyp);
175  }
176  }
177  else if (arg.iscomplex ())
178  {
179  if (arg.issparse ())
180  {
182 
183  MatrixType mattyp = args(0).matrix_type ();
184  result = m.inverse (mattyp, info, rcond, true, true);
185  args(0).matrix_type (mattyp);
186  }
187  else
188  {
190 
191  MatrixType mattyp = args(0).matrix_type ();
192  result = m.inverse (mattyp, info, rcond, true, true);
193  args(0).matrix_type (mattyp);
194  }
195  }
196  else
197  // Shouldn't get here since we checked for suitable arg earlier.
198  // Maybe for some user-defined classes?
199  err_wrong_type_arg ("inv", arg);
200  }
201 
202  octave_value_list retval (nargout > 1 ? 2 : 1);
203 
204  retval(0) = result;
205  if (nargout > 1)
206  retval(1) = (isfloat ? octave_value (frcond) : octave_value (rcond));
207 
208  if (nargout < 2)
209  {
210  bool is_singular;
211 
212  if (isfloat)
213  is_singular = ((frcond + 1.0f == 1.0f) || octave::math::isnan (frcond))
214  && ! arg.is_scalar_type ();
215  else
216  is_singular = ((rcond + 1.0 == 1.0) || octave::math::isnan (rcond))
217  && ! arg.is_scalar_type ();
218 
219  if (info == -1 || is_singular)
220  warn_singular_matrix (isfloat ? frcond : rcond);
221  }
222 
223  return retval;
224 }
225 
226 /*
227 ## Basic test for double/single matrices
228 %!assert (inv ([1, 2; 3, 4]), [-2, 1; 1.5, -0.5], 5*eps)
229 %!test
230 %! [xinv, rcond] = inv ([1,2;3,4]);
231 %! assert (xinv, [-2, 1; 1.5, -0.5], 5*eps);
232 %! assert (isa (rcond, "double"));
233 
234 %!assert (inv (single ([1, 2; 3, 4])), single ([-2, 1; 1.5, -0.5]),
235 %! 5* eps ("single"))
236 %!test
237 %! [xinv, rcond] = inv (single ([1,2;3,4]));
238 %! assert (xinv, single ([-2, 1; 1.5, -0.5]), 5* eps ("single"));
239 %! assert (isa (rcond, "single"));
240 
241 ## Basic test for integer inputs
242 %!assert (inv (int32 (2)), 0.5)
243 %!assert (inv (uint32 (2)), 0.5)
244 %!assert (inv (int64 (2)), 0.5)
245 %!assert (inv (uint64 (2)), 0.5)
246 
247 ## Normal scalar cases
248 %!assert (inv (2), 0.5)
249 %!test
250 %! [xinv, rcond] = inv (2);
251 %! assert (xinv, 0.5);
252 %! assert (rcond, 1);
253 %!assert (inv (single (2)), single (0.5))
254 %!test
255 %! [xinv, rcond] = inv (single (2));
256 %! assert (xinv, single (0.5));
257 %! assert (rcond, single (1));
258 %!assert (inv (complex (1, -1)), 0.5+0.5i)
259 %!test
260 %! [xinv, rcond] = inv (complex (1, -1));
261 %! assert (xinv, 0.5+0.5i);
262 %! assert (rcond, 1);
263 %!assert (inv (complex (single (1), -1)), single (0.5+0.5i))
264 %!test
265 %! [xinv, rcond] = inv (complex (single (1), -1));
266 %! assert (xinv, single (0.5+0.5i));
267 %! assert (rcond, single (1));
268 
269 ## Test special inputs
270 ## Empty matrix
271 %!assert (inv (zeros (2,0)), [])
272 
273 ## Scalar "0"
274 %!assert (inv (0), Inf)
275 %!test
276 %! [xinv, rcond] = inv (0);
277 %! assert (xinv, Inf);
278 %! assert (rcond, 0);
279 %!assert (inv (single (0)), single (Inf))
280 %!test
281 %! [xinv, rcond] = inv (single (0));
282 %! assert (xinv, single (Inf));
283 %! assert (rcond, single (0));
284 %!assert (inv (complex (0, 0)), Inf)
285 %!test
286 %! [xinv, rcond] = inv (complex (0, 0));
287 %! assert (xinv, Inf);
288 %! assert (rcond, 0);
289 %!assert (inv (complex (single (0), 0)), single (Inf))
290 %!test
291 %! [xinv, rcond] = inv (complex (single (0), 0));
292 %! assert (xinv, single (Inf));
293 %! assert (rcond, single (0));
294 ## NOTE: Matlab returns +Inf for -0 input, but it returns -Inf for 1/-0.
295 ## These should be the same, and in Octave they are.
296 %!assert (inv (-0), -Inf)
297 %!test
298 %! [xinv, rcond] = inv (-0);
299 %! assert (xinv, -Inf);
300 %! assert (rcond, 0);
301 
302 ## Scalar "Inf"
303 %!assert (inv (Inf), 0)
304 %!test
305 %! [xinv, rcond] = inv (Inf);
306 %! assert (xinv, 0);
307 %! assert (rcond, 0);
308 %!assert (inv (single (Inf)), single (0))
309 %!test
310 %! [xinv, rcond] = inv (single (Inf));
311 %! assert (xinv, single (0));
312 %! assert (rcond, single (0));
313 %!assert (inv (complex (1, Inf)), 0)
314 %!test
315 %! [xinv, rcond] = inv (complex (1, Inf));
316 %! assert (xinv, 0);
317 %! assert (rcond, 0);
318 %!assert (inv (complex (single (1), Inf)), single (0))
319 %!test
320 %! [xinv, rcond] = inv (complex (single (1), Inf));
321 %! assert (xinv, single (0));
322 %! assert (rcond, single (0));
323 
324 ## Scalar "NaN"
325 %!assert (inv (NaN), NaN)
326 %!test
327 %! [xinv, rcond] = inv (NaN);
328 %! assert (xinv, NaN);
329 %! assert (rcond, NaN);
330 %!assert (inv (single (NaN)), single (NaN))
331 %!test
332 %! [xinv, rcond] = inv (single (NaN));
333 %! assert (xinv, single (NaN));
334 %! assert (rcond, single (NaN));
335 %!assert (inv (complex (1, NaN)), complex (NaN, NaN))
336 %!test
337 %! [xinv, rcond] = inv (complex (1, NaN));
338 %! assert (xinv, complex (NaN, NaN));
339 %! assert (rcond, NaN);
340 %!assert (inv (complex (single (1), NaN)), complex (single (NaN), NaN))
341 %!test
342 %! [xinv, rcond] = inv (complex (single (1), NaN));
343 %! assert (xinv, complex (single (NaN), NaN));
344 %! assert (rcond, single (NaN));
345 
346 ## Matrix special values
347 ## Matrix of all zeroes
348 %!warning <matrix singular> assert (inv (zeros (2,2)), Inf (2,2))
349 %!test
350 %! [xinv, rcond] = inv (zeros (2,2));
351 %! assert (xinv, Inf (2,2));
352 %! assert (rcond, 0);
353 ## Matrix of all Inf
354 %!warning <rcond = > assert (inv (Inf (2,2)), NaN (2,2))
355 %!test
356 %! [xinv, rcond] = inv (Inf (2,2));
357 %! assert (xinv, NaN (2,2));
358 %! assert (rcond, NaN);
359 ## Matrix of all NaN
360 %!warning <rcond = > assert (inv (NaN (2,2)), NaN (2,2))
361 %!test
362 %! [xinv, rcond] = inv (NaN (2,2));
363 %! assert (xinv, NaN (2,2));
364 %! assert (rcond, NaN);
365 
366 ## Special diagonal matrices
367 %!test
368 %! fail ("A = inv (diag ([1, 0, 1]))", "warning", "matrix singular");
369 %! assert (A, diag ([Inf, Inf, Inf]));
370 
371 ## Special sparse matrices
372 %!testif HAVE_UMFPACK <*56232>
373 %! fail ("A = inv (sparse ([1, 2;0 ,0]))", "warning", "matrix singular");
374 %! assert (A, sparse ([Inf, Inf; 0, 0]));
375 
376 %!testif HAVE_UMFPACK <*56232>
377 %! fail ("A = inv (sparse ([1i, 2;0 ,0]))", "warning", "matrix singular");
378 %! assert (A, sparse ([Inf, Inf; 0, 0]));
379 
380 %!testif HAVE_UMFPACK <*56232>
381 %! fail ("A = inv (sparse ([1, 0, 0; 0, 0, 0; 0, 0, 1]))",
382 %! "warning", "matrix singular");
383 %! assert (A, sparse ([Inf, 0, 0; 0, 0, 0; 0, 0, Inf]));
384 
385 %!error <Invalid call> inv ()
386 %!error <Invalid call> inv ([1, 2; 3, 4], 2)
387 %!error <wrong type argument> inv ("Hello World")
388 %!error <wrong type argument> inv ({1})
389 %!error <wrong type argument> inv (true)
390 %!error <must be a square matrix> inv ([1, 2; 3, 4; 5, 6])
391 %!error <inverse of the null matrix not defined> inv (sparse (2, 2, 0))
392 %!error <inverse of the null matrix not defined> inv (diag ([0, 0]))
393 %!error <inverse of the null matrix not defined> inv (diag (complex ([0, 0])))
394 */
395 
396 DEFALIAS (inverse, inv);
397 
OCTAVE_END_NAMESPACE(octave)
OCTAVE_API double rcond(void) const
Definition: CDiagMatrix.cc:507
OCTAVE_API ComplexDiagMatrix inverse(octave_idx_type &info) const
Definition: CDiagMatrix.cc:311
OCTAVE_API DiagMatrix inverse(void) const
Definition: dDiagMatrix.cc:227
OCTAVE_API double rcond(void) const
Definition: dDiagMatrix.cc:345
OCTAVE_API FloatComplexDiagMatrix inverse(octave_idx_type &info) const
OCTAVE_API float rcond(void) const
OCTAVE_API FloatDiagMatrix inverse(void) const
Definition: fDiagMatrix.cc:227
OCTAVE_API float rcond(void) const
Definition: fDiagMatrix.cc:323
Definition: dMatrix.h:42
OCTAVE_API PermMatrix inverse(void) const
Definition: PermMatrix.cc:114
SparseMatrix sparse_matrix_value(bool frc_str_conv=false) const
Definition: ov.h:945
bool isreal(void) const
Definition: ov.h:783
bool issparse(void) const
Definition: ov.h:798
DiagMatrix diag_matrix_value(bool force=false) const
Definition: ov.h:955
FloatDiagMatrix float_diag_matrix_value(bool force=false) const
Definition: ov.h:958
ComplexMatrix complex_matrix_value(bool frc_str_conv=false) const
Definition: ov.h:916
octave_idx_type rows(void) const
Definition: ov.h:590
FloatComplexDiagMatrix float_complex_diag_matrix_value(bool force=false) const
Definition: ov.h:965
bool isnumeric(void) const
Definition: ov.h:795
bool is_scalar_type(void) const
Definition: ov.h:789
bool is_diag_matrix(void) const
Definition: ov.h:676
octave_idx_type columns(void) const
Definition: ov.h:592
ComplexDiagMatrix complex_diag_matrix_value(bool force=false) const
Definition: ov.h:961
FloatMatrix float_matrix_value(bool frc_str_conv=false) const
Definition: ov.h:901
PermMatrix perm_matrix_value(void) const
Definition: ov.h:968
bool isempty(void) const
Definition: ov.h:646
bool is_single_type(void) const
Definition: ov.h:743
Matrix matrix_value(bool frc_str_conv=false) const
Definition: ov.h:898
bool is_perm_matrix(void) const
Definition: ov.h:679
FloatComplexMatrix float_complex_matrix_value(bool frc_str_conv=false) const
Definition: ov.h:920
bool iscomplex(void) const
Definition: ov.h:786
SparseComplexMatrix sparse_complex_matrix_value(bool frc_str_conv=false) const
Definition: ov.h:949
OCTAVE_BEGIN_NAMESPACE(octave) static octave_value daspk_fcn
OCTINTERP_API void print_usage(void)
Definition: defun-int.h:72
#define DEFUN(name, args_name, nargout_name, doc)
Macro to define a builtin function.
Definition: defun.h:56
#define DEFALIAS(alias, name)
Macro to define an alias for another existing function name.
Definition: defun.h:160
void err_square_matrix_required(const char *fcn, const char *name)
Definition: errwarn.cc:122
void err_wrong_type_arg(const char *name, const char *s)
Definition: errwarn.cc:166
void warn_singular_matrix(double rcond)
bool isnan(bool)
Definition: lo-mappers.h:178
T octave_idx_type m
Definition: mx-inlines.cc:773
return octave_value(v1.char_array_value() . concat(v2.char_array_value(), ra_idx),((a1.is_sq_string()||a2.is_sq_string()) ? '\'' :'"'))
octave_value_list ovl(const OV_Args &... args)
Construct an octave_value_list with less typing.
Definition: ovl.h:211