linsolve
Solve linear system of equations
Syntax
X = linsolve(A,B)
X = linsolve(A,B,opts)
Description
X = linsolve(A,B)
solves the linear systemA*X = B
using LU factorization with partial pivoting when A is square and QR factorization with column pivoting otherwise. The number of rows ofA
must equal the number of rows ofB
. IfA
is m-by-n andB
is m-by-k, thenX
is n-by-k.linsolve
returns a warning ifA
is square and ill conditioned or if it is not square and rank deficient.
[X, R] = linsolve(A,B)
suppresses these warnings and returnsR
, which is the reciprocal of the condition number ofA
ifA
is square, or the rank ofA
ifA
is not square.
X = linsolve(A,B,opts)
solves the linear systemA*X = B
orA'*X = B
, using the solver that is most appropriate given the properties of the matrixA
, which you specify inopts
. For example, ifA
is upper triangular, you can setopts.UT = true
to makelinsolve
use a solver designed for upper triangular matrices. IfA
has the properties inopts
,linsolve
is faster thanmldivide
, becauselinsolve
does not perform any tests to verify thatA
has the specified properties.
Notes
IfA
does not have the properties that you specify inopts
,linsolve
returns incorrect results and does not return an error message. If you are not sure whetherA
has the specified properties, usemldivide
instead.
For small problems, there is no speed benefit in usinglinsolve
on triangular matrices as opposed to using themldivide
function.
TheTRANSA
field of theopts
structure specifies the form of the linear system you want to solve:
If you set
opts.TRANSA = false
,linsolve(A,B,opts)
solvesA*X = B
.If you set
opts.TRANSA
=true
,linsolve(A,B,opts)
solvesA'*X = B
.
The following table lists all the field ofopts
and their corresponding matrix properties. The values of the fields ofopts
must belogical
和默认值fields isfalse
.
Field Name |
Matrix Property |
---|---|
|
Lower triangular |
|
Upper triangular |
|
Upper Hessenberg |
|
Real symmetric or complex Hermitian |
|
Positive definite |
|
General rectangular |
|
Conjugate transpose — specifies whether the function solves |
The following table lists all combinations of field values inopts
that are valid forlinsolve
. A true/false entry indicates thatlinsolve
accepts either true or false.
LT |
UT |
UHESS |
SYM |
POSDEF |
RECT |
TRANSA |
---|---|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Examples
The following code solves the systemA'x = b
for an upper triangular matrixA
using bothmldivide
andlinsolve
.
A = triu(rand(5,3)); x = [1 1 1 0 0]'; b = A'*x; y1 = (A')\b opts.UT = true; opts.TRANSA = true; y2 = linsolve(A,b,opts) y1 = 1.0000 1.0000 1.0000 0 0 y2 = 1.0000 1.0000 1.0000 0 0
Note
If you are working with matrices having different properties, it is useful to create an options structure for each type of matrix, such asopts_sym
. This way you do not need to change the fields whenever you solve a system with a different type of matrixA
.