Message Boards Message Boards

Minimize a function using the results from NDSolve

Posted 4 years ago

I get some results z1 from an equation

  s1 = y''[x] + Sin[y[x]] y[x];
    sol1 = NDSolve[{s1 == 0, y[0] == 1, y'[0] == 0}, y, {x, 0, 30}];
    sy[x_] = {y[x]} /. s;
    z1 = Table[Take[sy[x]], {x, 5, 30, 5}]
{{{-4.56095}}, {{0.999889}}, {{-4.55976}}, {{0.999555}},{{-4.55738}}, {{0.998999}}}

Now a new equation s2 contains a and b

s2 = a*y2''[x] + b*Sin[y2[x]] y2[x]

The results z2 should be solved using the same method.

sol2 = NDSolve[{s2 == 0, y2[0] == 1, y2'[0] == 0}, y2, {x, 0, 30}];
sy2[x_] = {y2[x]} /. s;
z2 = Table[Take[sy2[x]], {x, 5, 30, 5}]

Then I want to minimize (z1-z2).(z1-z2) and find a and b

Nminimize[(z1 - z2).(z1 - z2), {a, b}]

I know my codes can't work, but I'm trying to express thought. I'm new to Mathematica. I really appreciate your help.

POSTED BY: Yz Wu
3 Replies

You probably have a misconception of what Take does. Please have a look at the documentation.

POSTED BY: Gianluca Gorni
Posted 4 years ago

Thank you. But When I try to run a complicated case, I meet another problem,

z1 = Table[Take[ysol[[1]], {Nn + 1, 2 Nn}].u2n[L/2], {t, 5, 20, 5}]
{0.267999, 0.483416, 0.601376, 0.661358}

my function with unknowns is

invysol = ParametricNDSolveValue[Thread[Join[inveqD, invicD] == 0], {invq[t]}, {t, 0, tf}, {x1, x2, 
   x3, x4}]

But when I want to make z2, an error comes,

z2 = Table[Take[First[invysol], {Nn + 1, 2 Nn}].u2n[L/2], {t, 5, 20, 1}]
Take::normal: Nonatomic expression expected at position 1 in Take[1,{6,10}].
Take::normal: Nonatomic expression expected at position 1 in Take[1,{6,10}].
Take::normal: Nonatomic expression expected at position 1 in Take[1,{6,10}].
General::stop: Further output of Take::normal will be suppressed during this calculation.

It seems I can't use Take in the ParametricNDSolveValue function. Do you know how to solve it?

POSTED BY: Yz Wu

You can do it with ParametricNDSolveValue:

s1 = y''[x] + Sin[y[x]] y[x];
sy = NDSolveValue[{s1 == 0, y[0] == 1, y'[0] == 0}, y, {x, 0, 30}];
z1 = Table[sy[x], {x, 5, 30, 5}];
s2 = a*y2''[x] + b*Sin[y2[x]] y2[x];
sy2 = ParametricNDSolveValue[{s2 == 0, y2[0] == 1, y2'[0] == 0}, 
   y2, {x, 0, 30}, {a, b}];
z2 = Table[sy2[a, b][x], {x, 5, 30, 5}];
NMinimize[(z1 - z2).(z1 - z2), {a, b}]
POSTED BY: Gianluca Gorni
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract