# Solving a 2nd order ODE

조회 수: 2(최근 30일)
Yuzhe Mei 18 Oct 2019
댓글: darova 18 Oct 2019
Hi,
I was trying to solve a 2nd order ODE with expression like this:
where m and k are constants. I've tried dsolve:
syms x x0 x_0 k m
Dx = diff(x);
ode = diff(x,2) == -k*x/m;
cond1 = x(0) == x0;
cond2 = Dx(0) == x_0;
conds = [cond1 cond2];
dSol(x) = dsolve(ode,conds);
ySol = simplify(ySol)
But that didn't work. Can anyone help me out with this? Thank you so much!

### 채택된 답변

John D'Errico 18 Oct 2019
It is arguably bad notation to have x0 and x_0 as two variables that mean very different things. Confusing as hell, and if you do this in the future, expect to have buggy code, because you were yourself confused as you wrote it.
So in what I'll do, I'll use the variable xdot0 as the derivative of x, at time 0, just as x0 is the value of x, at time 0.
But that is not your problem here. What is your problem is in understanding that x will actually be a function of some variable. I'll call it t. You need to tell MATLAB that here, as you have used things like x(0), but you never told the symbolic toolbox that x is a FUNCTION (not a matlab function m-file) but a mathematical, unknown function.
So let me make some minor changes to your code.
syms t x(t) x0 xdot0 k m
Dx = diff(x);
ode = diff(x,2) == -k*x/m;
cond1 = x(0) == x0;
cond2 = Dx(0) == xdot0;
conds = [cond1 cond2];
dSol = dsolve(ode,conds);
My changes were very small, which means you were going in the right direction. The first serious problem was really in that you needed to define x properly in the very beginning. For example, now, when I write x(0, or Dx(0), we see this:
>> Dx(0)
ans =
subs(diff(x(t), t), t, 0)
>> x(0)
ans =
x(0)
So MATLAB understands they are now functions of t, and to evaluate them at t=0.
Your next error was in the dsolve line. You cannot write
dSol(x) = dsolve(ode,conds);
dSol does not even exist yet anyway. And while you are thingking it will be somehow a function, you cannot write that line as you tried. Instead, see that I just wrote is as
dSol = dsolve(ode,conds);
The final call to simplify did nothing to change the result.
dSol =
(exp((t*(-k*m)^(1/2))/m)*(m*xdot0 + x0*(-k*m)^(1/2)))/(2*(-k*m)^(1/2)) - (exp(-(t*(-k*m)^(1/2))/m)*(m*xdot0 - x0*(-k*m)^(1/2)))/(2*(-k*m)^(1/2))
But as you see, now there is a valid result.

#### 댓글 수: 2

Yuzhe Mei 18 Oct 2019
I get it now. Thank you so much for sharing your answer:D!
darova 18 Oct 2019