MATLAB求解代数方程、微分方程的一些常用指令

MATLAB版本:R2015b

1.求解符号矩阵的行列式、逆、特征值、特征向量

A = sym('[a11, a12; a21, a22]');
deltaA = det(A)
invA = inv(A)
[V, D] = eig(A) %V的列向量为特征向量,D的主对角线元素为相应的特征值

2.求解代数方程的解析解

syms a b c
x = solve('a * x^2 + b * x + c = 0', 'x')

3.求解微分方程(组)的解析解

syms x y
Y1 = dsolve('D2y - 3 * Dy + 2 * y = x', 'x') %通解
Y2 = dsolve('D2y - 3 * Dy + 2 * y = x', 'y(0) = 1', 'y(1) = 2', 'x') %特解

syms f g
[f, g] = dsolve('Df = f + g', 'Dg = g - f', 'Df(0) = 1', 'Dg(0) = 1')

4.泰勒展开

syms x y;
y=sin(x);
taylor(y, x, 'ExpansionPoint', 0, 'Order', 4)

5.多项式拟合

x=linspace(0, 2 * pi, 20);
y = sin(x);
P = polyfit(x, y, 3);
y1 = polyval(P, x);
plot (x, y, ':o', x, y1, '-*')
legend('sin(x)', 'fit')

6.数值法求解微分方程(组)

已知y(0)=2,y'(0)=y"(0)=0.试求方程y'''-e^(-ty)+tyy''+t^2y^2y'=0的数值解。

第一种方式,使用匿名函数:

f = @(t, x)[x(2); x(3); exp(-t * x(1)) - t * x(1) * x(3) - t^2 * x(1)^2 * x(2)];
x0 = [2; 0; 0];
tf = 4;
a1 = [2, 3];
a2 = 8;
options = odeset;
options.RelTol = 1e-7;
[t, x] = ode45(f, [0, tf], x0, options);
plot(t, x)

第二种方式,使用M-函数:

(必须)新建一个M文件,编写M-函数

function dx = fun(t, x, r, g)
dx = [r(1) + x(2); r(2) * x(3); g + exp(-t * x(1)) - t * x(1) * x(3) - t^2 * x(1)^2 * x(2)];

在另一个文件中

x0 = [2; 0; 0];
tf = 4;
r = [2, 3];
g = 8;
options = odeset;
options.RelTol = 1e-7;
[t, x] = ode45(@fun, [0, tf], x0, options, r, g);
plot(t, x)

求得的t是一个NX1的列向量,x是一个NX3的矩阵。

相似的函数还有:ode15s, ode23, ode23s, ode23t, ode23tb, ode113.

原文地址:https://www.cnblogs.com/pursuiting/p/6083301.html