I'm having trouble making a function that uses the result of NDSolve
:
c=1/4;
soln = NDSolve[{c^2*D[u[x, t], x, x] == D[u[x, t], t, t],
u[x, 0] == UnitTriangle[2*x - 1],
Derivative[0, 1][u][x, 0] == 0, u[0, t] == 0,
u[1, t] == 0}, u, {x, 0, 1}, {t, 0, 4/c},
Method -> {"PDEDiscretization" -> {"MethodOfLines",
"SpatialDiscretization" -> "FiniteElement"}}]
energy[(t_)?NumericQ] :=
(1/2)*NIntegrate[Evaluate[
D[u[x, t]^2, t] + c^2*D[u[x, t]^2, x] /.
First[soln]], {x, 0, 1},
MaxRecursion -> 10, Method -> "LocalAdaptive"];
Evaluating energy[0.5]
gives the error: General::ivar: 0.5` is not a valid variable.
Inspecting the definition with ??energy
shows Evaluate
didn't work.
After changing the definition to:
expr = D[u[x, t]^2, t] + c^2*D[u[x, t]^2, x] /. First[soln];
energy[(t_)?NumericQ] := (1/2)*NIntegrate[Evaluate[expr],
{x, 0, 1}, MaxRecursion -> 10,
Method -> "LocalAdaptive"];
using energy[t]
inside Table
and Plot
work, but energy[0.5]
gives a NIntegrate::inumri
error with NIntegrate
left unevaluated and containing exactly what expr
is.