在Matlab中求解线性方程 [英] Solving Linear Equation in Matlab
问题描述
我想在Matlab中求解#n个线性方程组AX=bi
(对于#nb而言),其中b
循环变化,而A
是常数.
I wanna solve #n linear equations AX=bi
(for #n b's) in Matlab which b
changes in a loop and A
is constant.
一种快速的方法是在循环之前计算A
的逆,并且在循环体内只需从inv(A)*b
获得X
,但是由于矩阵A
是奇异的,所以我感到很糟糕回答!
当然,数值解A/b
提供了一个很好的答案,但要点是,在#n
循环中计算#n
不同的X
的时间花费了很长的时间.
One way which is fast, is to compute the inverse of A
before the loop and in the loop body just get X
from inv(A)*b
, but because the matrix A
is singular, I get an awful answer!
Of course, the numerical solution A/b
gives a good answer, but the point is that it takes a long time to compute #n
different X
's in #n
loops.
我想要的是一种既准确又快速的解决方案.
What I want is a solution which can be both accurate and fast.
推荐答案
我实际上认为这是一个好问题,除了错别字和矩阵奇异性问题.有几种解决方法,Tim Davis在MATLAB Central上的 factorize
提交覆盖了所有角度.
I actually think this is a good question, typos and issues of matrix singularity aside. There are a few good ways to handle this, and Tim Davis' factorize
submission on MATLAB Central covers all the angles.
但是,仅供参考,让我们在本机MATLAB中自行进行操作,从A
是正方形的情况开始.首先,有两种建议的方法(inv
和\
,mldivide
):
However, just for reference, let's do it on our own in native MATLAB, starting with the case where A
is square. First, there are the two methods you suggested (inv
and \
,mldivide
):
% inv, slow and inacurate
xinvsol = inv(A)*b;
norm(A*xinvsol - b ,'fro')
% mldivide, faster and accurate
xref = A\b;
norm(A*xref - b ,'fro')
但是,如果像您说的那样A
不变,只需分解A
并求解新的b
即可!假设A
是对称正定:
But if like you said A
does not change, just factorize A
and solve for new b
! Say A
is symmetric positive definite:
L = chol(A,'lower'); % Cholesky factorization
% mldivide, much faster (not counting the chol factorization) and most accurate
xcholbs= L'\(L\b); %'
norm(A*xcholbs - b ,'fro')
% linsolve, fastest (omits checks for matrix configuration) and most accurate
sol1 = linsolve(L, b, struct('LT',true));
xcholsolv = linsolve(L, sol1, struct('LT',true,'TRANSA',true));
norm(A*xcholsolv - b ,'fro')
如果A
不是对称正定的,则将LU分解用于方阵,否则将QR用于.同样,您可以自己完成所有操作,也可以只使用 Tim Davis出色的分解函数.
If A
is not symmetric positive definite, then you'd use LU decomposition for a square matrix or QR otherwise. Again, you can do it all yourself, or you can just use Tim Davis' awesome factorize functions.
这篇关于在Matlab中求解线性方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!