Suppose that $q[t]$ is obtained by NDSolve
as an InterpolatingFunction
, and I want to define $Q[t]$ to be some function of $q[t]$, say $\sqrt{q[t]}$. How can I define it in such a way that I become able to plot its time derivative for example?
2 Answers
I might be grossly mistaken, but what is preventing you to compute a function of an interpolating function?
NDSolve[{x''[t] + .2x'[t] + x[t] == 0, x[0] == 1, x'[0] == .4}, x[t], {t, 0, 10}]
InterpolatingFunction[{{0,10}},<>][t]
Define your function in this way
f[t_] = x[t] /. %[[1]];
Then you can compute functions of it, like it was another function
g[t_] = Sqrt[f[t]]
Sqrt[ InterpolatingFunction[{{0,10}},<>][t] ]
Computing the derivative is using the composition rule
g'[t]
InterpolatingFunction[{{0,10}},<>][t]/(2 Sqrt[InterpolatingFunction[{{0,10}},<>][t])
and like other functions you might have warnings when you try to plot imaginary values... So might be forced to use Abs
or Re
or Im
.
Plot[{Abs[g[t]], Abs[g'[t]]}, {t, 0, 10}, Frame -> True]
-
$\begingroup$ Hmmmmm... this is embarrassing :) Who would have thought of this... $\endgroup$ Dec 9, 2013 at 21:30
-
$\begingroup$ A long time ago, in a galaxy far, far away, Mathematica developers used to write articulated... articles in The Mathematica Journal about the new features introduced with new versions. But that was, as I've said, a long time ago. These days there is much less... articulation :-). Anyway, your approach shows an easy way to extract data points from interpolating functions. The OP will certainly appreciate it. $\endgroup$– PeltioDec 9, 2013 at 21:46
-
$\begingroup$ @Peltio Thanks Peltio. Please note the edit in the question. $\endgroup$– TarekDec 10, 2013 at 11:25
Needs@"DifferentialEquations`InterpolatingFunctionAnatomy`";
if = y /. First@NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == 1}, y, {x, 0, 30}]
dataY = InterpolatingFunctionValuesOnGrid@if;
dataX = Flatten@InterpolatingFunctionGrid@if;
{
ListPlot@Transpose@{dataX, dataY},
ListPlot@Transpose@{dataX, dataY^3}
}
InterpolatingFunction[{{0., 30.}}, <>]
-
1$\begingroup$ I have never hear about
InterpolatingFunctionAnatomy
+1! However there is simpler method:if["Coordinates"]
andif["ValuesOnGrid"]
make the job. A list of all possible options:PropertyList[if]
. $\endgroup$ Dec 10, 2013 at 18:37
ifun
is your interpolating function, you could for example writeSqrt[ifun[#]] &@t
to getQ[t]
andSqrt[ifun[#]] &'@t
to getQ'[t]
. $\endgroup$InterpolatingFunctionAnatomy
. It has functions to extract datapoints from anInterpolatingFunction
object. $\endgroup$G[p,Q]
as a function of unevaluatedp
andQ
, compute its partial derivatives wrtp
andQ
and only then substitute theInterpolatingFunction
s for their values. $\endgroup$G[p[t], Q[t]]
. $\endgroup$