So I have an ODE that needs to be solved a few thousand times on MATLAB and am wondering what the most efficient method to use would be. I am changing a constant term each time. My ODE is of the form $$x''= f(x) + g(t) + x'$$ With initial conditions of $x(0)=x0$ and $x'(0)=0$. $$f(x)=\frac{a^2}{4b}-a(\frac{d^2}{dx^2}(\frac{x}{\sqrt{c+x^2}}))$$ $$g(t)=d \cos{\omega t}$$ with $a$ being the constant that is being varied, $b$, $c$, and $d$ are constant for every iteration.

Since $f(x)$ is a nasty term involving derivatives W.R.T. $x$, I am solving it for a bunch of $x$ values before integration and using the value nearest to the previous ODE solution (accuracy here doesn't seem to be a problem), pulling the corresponding $f(x)$ value from an array. The constant term that is varied for each solver iteration is included in $f(x)$. $f(x)$ is solved with a bunch of matrix operations so it's relatively quick but since my $f(x)$ solutions are in an array corresponding to the constant term and x value, I have to solve using ode45 in a for loop which takes a long time (ode45 accepts arrays as systems of ODEs and doesn't have a 'dim' parameter option so a loop must be used as far as I know.) I know the range that the solutions will be in and it is non-stiff. Can anyone recommend a faster way to do this? Thanks.

  • $\begingroup$ Can you be a bit more specific about $f$ and $g$ and the constant you are changing? $\endgroup$ – David May 20 '16 at 2:04
  • $\begingroup$ I would make an anonymous function $f$ like this: syms x a b c, f=matlabFunction(simplify(a^2/(4*b^2)-a*diff(x/sqrt(c+x^2),x,2)));, then g=@(d,w,t) d*cos(w*t);, then I think you could just do [t,x]=ode45(@(t,x)[x(2);f(a,b,c,x(1))+g(d,w,t)+x(2)],[0 T],[x0;0]); in each iteration after you set the values of a, b, c, d and w. If you're just changing $a$ this should be quite fast depending on the rest of the parameters. $\endgroup$ – David May 20 '16 at 2:37
  • $\begingroup$ That's pretty much what I'm doing now; it uses an anonymous function since its a second order ODE but $f(x)$ has the derivative part so unless I can update the input as ode45 solves for $x$s, the $f(x)$ term must be solved numerically before. $\endgroup$ – Tburke2 May 20 '16 at 2:45
  • $\begingroup$ You can explicitly calculate $f(x)$ because it's not a time derivative. That's what my code does, you don't have to solve it numerically, you can write $f(x)$ explicitly, there's no work needed at each iteration $\endgroup$ – David May 20 '16 at 2:56
  • $\begingroup$ Your ODE is just $$x''-x'=\frac{a^2}{4b^2}+\frac{3acx}{(x^2+c)^{5/2}}+d\cos(\omega t),$$ nothing fancy. $\endgroup$ – David May 20 '16 at 3:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.