2

I have a complex valued ODE.

 ysol = NDSolveValue[{y'[x] == I Sin[y[x] Cos[x y[x]]], y[0] == .5}, y, {x, 0, 30}];
 Plot[Abs[ysol[x]], {x, 0, 30}, PlotRange -> All]

The function $\left|y(t)\right|$ is plotted below:

enter image description here

I want to calculate the derivative of this function i.e., $\left|y(t)\right|'$. How can that be done? I tried the following but it does not work this way.

Plot[D[Abs[ysol[x]],x], {x, 0, 30}, PlotRange -> All]
  • Abs[z] is not a differentiable function of the (complex) variable z. Since ysol[x] appears to be positive, why not use D[ysol[x], x]? Alternatively, use RealAbs[..] instead of Abs[..]. – Michael E2 Jul 12 '21 at 05:11
  • Also, see this Q&A and its duplicate for why you should use Evaluate in Plot[Evaluate[D[...]],...] -- Alternatively, use prime: Plot[ysol'[x], {x, 0, 30},...] – Michael E2 Jul 12 '21 at 05:14
  • @MichaelE2 ysol[x] is a complex quantity here. The graph that is plotted above, I just want to differentiate it. Is it just because it is complex that calculating its derivative is not possible? – diffusiondiver11 Jul 12 '21 at 05:32
  • 1
    Sorry about that, I guess it's getting late here and I didn't read carefully. Maybe this?: Plot[Re[ysol[x] Conjugate[ysol'[x]]]/Abs[ysol[x]], {x, 0, 30}, PlotRange -> All, Exclusions -> None] – Michael E2 Jul 12 '21 at 05:57

3 Answers3

3

I suggest a more general approach that can be used in more complicated situations. The idea is to re-interpolate the desired functions

xmesh = ysol["Coordinates"][[1]];
asol = Interpolation[Table[{xi, Abs[ysol[xi]]}, {xi, xmesh}]];

Now you can easily plot the function and its derivative

Plot[{asol[x], asol'[x]}, {x, 0, 30}, PlotRange -> All]

enter image description here

yarchik
  • 18,202
  • 2
  • 28
  • 66
2

Here's a quick way to do accurate numerical differentiation on Abs[y[x]]:

Needs["NumericalCalculus`"];
Plot[
 Evaluate@{
   Abs @ ysol[x]
   ND[Abs @ ysol[\[FormalX]], \[FormalX], x]
 },
 {x, 0, 30}, PlotRange -> All]

enter image description here

Sjoerd Smit
  • 23,370
  • 46
  • 75
1

Let u[x]+I*v[x] be ysol[x], so Abs[ysol[x] can be write as Sqrt[u[x]^2 + v[x]^2], we can difference Sqrt[u[x]^2 + v[x]^2] and then use replace:

rule={u[x] -> Re[ysol[x]], v[x] -> Im[ysol[x]], u'[x] -> Re[ysol'[x]], 
v'[x] -> Im[ysol'[x]]}
Plot[D[Sqrt[u[x]^2 + v[x]^2], x] /. {u[x] -> Re[ysol[x]], 
    v[x] -> Im[ysol[x]], u'[x] -> Re[ysol'[x]], 
    v'[x] -> Im[ysol'[x]]} // Evaluate, {x, 0, 30}, PlotRange -> All, 
 Exclusions -> None]

enter image description here

cvgmt
  • 72,231
  • 4
  • 75
  • 133