现在我假设您希望代码相当通用,所以我让它能够处理任何给定数量的方程和任何给定数量的变量,并且我没有手动计算。
请注意,符号工具箱的工作方式每年都会发生巨大变化,但希望这对您有用。现在可以将方程添加Eq1
到输入列表中,dSolve
但有两个问题:一个是dSolve
似乎更喜欢字符输入,第二个是dSolve
似乎没有意识到有 3 个自变量a
,b
和c
(它只看到 2 个变量,b
并且c
)。
为了解决第二个问题,我对原方程进行微分得到一个新的微分方程,这有三个问题:第一个是Matlab评估了a
关于t
as的导数0
,所以我不得不a
用a(t)
和替换为b
和c
(我称之为)a(t)
的长版本a
。第二个问题是 Matlab 使用了不一致的表示法,而不是表示a
as的导数Da
,它表示它,diff(a(t), t)
因此我不得不用前者替换后者,例如 for b
and c
; 这给了我Da = Db + Dc
。最后一个问题是系统现在尚未确定,所以我必须得到初始值,在这里我可以解决a(0)
但 Matlab 似乎对使用a(0) = b(0) + c(0)
.
现在回到最初的第一个问题,要解决我必须将每个 sym 转换回 char 的问题。
这是代码
function SolveExample
syms a b c y C1 C2 t;
Eq1 = sym('a = b + c');
dEq1 = 'Db = 1/C1*y(t)';
dEq2 = 'Dc = 1/C2*y(t)';
[dEq3, initEq3] = ...
TurnEqIntoDEq(Eq1, [a b c], t, 0);
% In the most general case Eq1 will be an array
% and thus DEq3 will be one too
dEq3_char = SymArray2CharCell(dEq3);
initEq3_char = SymArray2CharCell(initEq3);
% Below is the same as
% dsolve(dEq1, dEq2, 'Da = Db + Dc', ...
% 'b(0)=0','c(0)=0', 'a(0) = b(0) + c(0)', 't');
[sol_dEq1, sol_dEq2, sol_dEq3] = dsolve(...
dEq1, dEq2, dEq3_char{:}, ...
'b(0)=0','c(0)=0', initEq3_char{:}, 't')
end
function [D_Eq, initEq] = ...
TurnEqIntoDEq(eq, depVars, indepVar, initialVal)
% Note that eq and depVars
% may all be vectors or scalars
% and they need not be the same size.
% eq = equations
% depVars = dependent variables
% indepVar = independent variable
% initialVal = initial value of indepVar
depVarsLong = sym(zeros(size(depVars)));
for k = 1:numel(depVars)
% Make the variables functions
% eg. a becomes a(t)
% This is so that diff(a, t) does not become 0
depVarsLong(k) = sym([char(depVars(k)) '(' ...
char(indepVar) ')']);
end
% Next make the equation in terms of these functions
eqLong = subs(eq, depVars, depVarsLong);
% Now find the ODE corresponding to the equation
D_EqLong = diff(eqLong, indepVar);
% Now replace all the long terms like 'diff(a(t), t)'
% with short terms like 'Da'
% otherwise dSolve will not work.
% First make the short variables 'Da'
D_depVarsShort = sym(zeros(size(depVars)));
for k = 1:numel(depVars)
D_depVarsShort(k) = sym(['D' char(depVars(k))]);
end
% Next make the long names like 'diff(a(t), t)'
D_depVarsLong = diff(depVarsLong, indepVar);
% Finally replace
D_Eq = subs(D_EqLong, D_depVarsLong, D_depVarsShort);
% Finally determine the equation
% governing the initial values
initEq = subs(eqLong, indepVar, initialVal);
end
function cc = SymArray2CharCell(sa)
cc = cell(size(sa));
for k = 1:numel(sa)
cc{k} = char(sa(k));
end
end
一些小注释,我将其更改为==
,=
因为这似乎是我们的 Matlab 版本之间的差异。我还添加了t
作为自变量dsolve
。我还假设您了解单元格、数字、线性索引等。