使用matlab求解线性方程
Ax = B 形式 A ,B为矩阵
(1) A为非奇异矩阵时,既有唯一解时
共有三种方法求解:
example clear all A = [3 -9; 2 4]; b = [-42; 2]; % three methods x = inv(A)*b % good x = A % better x = linsolve(A,b) % best
https://www.mathworks.com/help/matlab/ref/linsolve.html
syms a b c d e f M = [a b;c d]; rhs = [e;f]; z = inv(M)*rhs >> z = inv(M)*rhs z = (d*e)/(a*d - b*c) - (b*f)/(a*d - b*c) (a*f)/(a*d - b*c) - (c*e)/(a*d - b*c) >> z = M^-1*rhs z = (d*e)/(a*d - b*c) - (b*f)/(a*d - b*c) (a*f)/(a*d - b*c) - (c*e)/(a*d - b*c) >> z = linsolve(M,rhs) z = -(b*f - d*e)/(a*d - b*c) (a*f - c*e)/(a*d - b*c) >> M = [3 -9;2 4] >> rhs = [-42;2]; >> z = inv(M)*rhs z = -5.0000 3.0000 >> z = M^-1*rhs z = -5.0000 3.0000 >> z = linsolve(M,rhs) z = -5 3
(2)A为奇异矩阵时,且A阵和[A,C]阵秩相同,则该方程有无数个解;
可以用 x = null(A); 先求出系统的齐次方程AX = 0的基础解系,然后再用 x0 = pinv(A)*B 求出方程的一个特解
然后得出系统的通解:X =a(1) * x(:,1) + a(2) * X(:,2) + ..... + a(n-m) * x(:,n-m) + x0;
A = [1 2 3 4;2 2 1 1;2 4 6 8;4 4 2 2]; B = [1 3 2 6]'; C = [A,B];[rank(A) rank(B)]; syms a1 a2 ; Z = null(sym(A)); >> x0 = sym(pinv(A))*B; >> X = a1*Z(:,1)+a2*Z(:,2)+x0 %求出方程的解析解 X = 2*a1 + 3*a2 + 125/131 96/131 - (7*a2)/2 - (5*a1)/2 a1 - 10/131 a2 - 39/131 >> A*X-B ans = 0 0 0 0
此外,可以采用rref(C),C = [A,B];进行基本行变换,得出方程的解析解;
>> c = [A,B];D =rref(c) D = 1.000000000000000 0 -2.000000000000000 -3.000000000000000 2.000000000000000 0 1.000000000000000 2.500000000000000 3.500000000000000 -0.500000000000000 0 0 0 0 0 0 0 0 0 0
(3)若A和[A,B]矩阵的秩不同,则原方程就没有解,只能用x = pinv(A)*B求出方程的最小二乘解;
使用matlab求非线性方程
Equations and systems solver - MATLAB solve (mathworks.com)
Solve system of nonlinear equations - MATLAB fsolve (mathworks.com)
求解代数方程的符号解。
S = solve(eqn1,eqn2,...,eqnM,var1,var2,...,varN)
eqn 是符号表达式,可以是方程或不等式。vars是指定未知变量的符号变量表示。
fsolve 用来解决多个变量的非线性方程组。
X = fsolve(FUN,X0,OPTIONS)
syms x y >> sol = solve([x^2+y^2-20,y - x^2,x>0,y>0],[x,y]) sol = 包含以下字段的 struct: x: [1×1 sym] y: [1×1 sym] >> sol.x ans = 2 >> sol.y ans = 4
还可以使用matlab函数或者匿名函数来描述方程
function F=myFunction(z) x = z(1); y = z(2); F(1)=x^2+y^2-20; F(2)=y - x^2; end
clear all z_G = [1; 1]; z = fsolve(@myFunction, z_G); disp(z)
匿名函数形式-----因为匿名函数标准形式为为针对自变量x,所以要都写成x变量的形式
>> f= @(x)[x(1).^2+x(2).^2-20;x(2) - x(1).^2]; >> X0 =[1;1];X= fsolve(f,X0) X = 2.0000 4.0000
还可以设置求解精度,options
option =optimset;
option .TolX = 1e-20; option .TolFun = 1e-20;
x = fsolve(f,x0,option )