Mathematica Asked by freebird on January 13, 2021
I am trying to run a simple code on Mathematica. However, it is not running for some reason. What mistake am I making?
ClearAll {x, y, z, t, X, Y, a, b, c};
Manipulate[
X[t_] := a Cos[t];
Y[t_] := Sin[t];
sols =
{NDSolve[
{D[{u[t], v[t]}, t] == D[{{X[t], Y[t]}, {Y[t], -X[t]}}, t].{u[t], v[t]},
{u[0], v[0]} == {1, 0}},
{u[t], v[t]}, {t, 0, 10}],
NDSolve[
{D[{u[t], v[t]}, t] == D[{{X[t], Y[t]}, {Y[t], -X[t]}}, t].{u[t], v[t]},
{u[0], v[0]} == {0, 1}},
{u[t], v[t]}, {t, 0, 10}][[1]]};
GraphicsRow[{
ParametricPlot[Evaluate[{u[t], v[t]} /. sols], {t, 0, 10}],
Plot[Tr[{u[t], v[t]} /. sols], {t, 0, 10}]}]
{{a, 2}, 1, 5}]
What am I doing wrong?
The first thing I notice is there's a comma missing right before {{a, 2}, 1, 5}]
at the bottom. When I fix that, it tells me that it's trying to take the trace of a non-rectangular matrix. When I extract just the trace portion, it looks like you're trying to take the trace of an interpolating function. Are you trying to add the first interpolating function of u[t] to the second of v[t]? If so, you need to arrange {u[t], v[t]}/.sols
into a 2 x 2 matrix, rather than {{1}, 2}, {{3}, 4}
which is what I'm seeing. I'm not sure if the number of solutions you get might change, but I'm assuming they'll all be square matrices. If that's the case, then this should work for you:
Manipulate[
X[t_] := a Cos[t];
Y[t_] := Sin[t];
sols = {NDSolve[{D[{u[t], v[t]}, t] ==
D[{{X[t], Y[t]}, {Y[t], -X[t]}}, t].{u[t], v[t]}, {u[0],
v[0]} == {1, 0}}, {u[t], v[t]}, {t, 0, 10}],
NDSolve[{D[{u[t], v[t]}, t] ==
D[{{X[t], Y[t]}, {Y[t], -X[t]}}, t].{u[t], v[t]}, {u[0],
v[0]} == {0, 1}}, {u[t], v[t]}, {t, 0, 10}][[1]]};
GraphicsRow[{
ParametricPlot[Evaluate[{u[t], v[t]} /. sols], {t, 0, 10}],
Plot[
Tr[Partition[#, Sqrt[Length[#]]] &@ Flatten[{u[t], v[t]} /. sols]],
{t, 0, 10}
]
}],
{{a, 2}, 1, 5}
]
Answered by MassDefect on January 13, 2021
You might find ParametricNDSolveValue
a convenient alternative:
ClearAll[pndsv, X, Y]
X[t_] := a Cos[t]
Y[t_] := Sin[t]
pndsv = ParametricNDSolveValue[
{D[{u1[t], v1[t]}, t] == D[{{X[t], Y[t]}, {Y[t], -X[t]}}, t].{u1[t], v1[t]},
{u1[0], v1[0], u2[0], v2[0]} == {1, 0, 0, 1},
D[{u2[t], v2[t]}, t] == D[{{X[t], Y[t]}, {Y[t], -X[t]}}, t].{u2[t], v2[t]}},
{u1, v1, u2, v2}, {t, 0, 10}, {a}];
Manipulate[Row[{ParametricPlot[Evaluate[Partition[Through[pndsv[a] @ t], 2]],
{t, 0, 10}, PlotStyle -> {Red, Blue}, PlotRange -> All,
ImageSize -> Medium, AspectRatio -> 1, Axes -> False, Frame -> True],
Plot[Evaluate[Tr @ Partition[Through[pndsv[a] @ t], 2]], {t, 0, 10},
PlotStyle -> Orange, PlotRange -> All, ImageSize -> Medium,
AspectRatio -> 1, Axes -> False, Frame -> True]},
Spacer[10]],
{a, 1, 5, Appearance -> "Labeled"}]
Answered by kglr on January 13, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP