1
$\begingroup$

I've got problem with If statement. It doesn't work. I've never used Mathematica before, probably it's a problem with syntax.

wynik1 = 0
For[u = 0, u <= 1, u = u + 0.1, 
 s = NDSolve[{x1'[t] == u*(10*x2[t] - x1[t]), x1[0] == 1, 
    x2'[t] == u*(x1[t] - 10*x2[t]) - (1 - u)*x2[t], x2[0] == 0}, {x1, 
    x2}, {t, 0, 1}];
 wynik = 1 - Evaluate[{x1[1] /. s} + {x2[1] /. s}];
 If[wynik > wynik1, wynik1 = wynik; Print[wynik1]]]

Any ideas?

$\endgroup$
0

2 Answers 2

1
$\begingroup$

Since you are only interested in the values of your functions evaluated at a specific point, you may want to use ParametricNDSolveValue to approach your problem in a more direct way

First generate an implicit family of solutions of your differential system returning the values of x1[1] and x2[1] as a function of your parameter u:

Clear[u, x1, x2, t]
solutions = ParametricNDSolveValue[
   {
    x1'[t] == u*(10*x2[t] - x1[t]), x1[0] == 1, 
    x2'[t] == u*(x1[t] - 10*x2[t]) - (1 - u)*x2[t], x2[0] == 0
   },
   {x1[1], x2[1]}, {t, 0, 1}, u
   ];

Then calculate all pairs of values of x[1] and x[2] for each value of $u$ of interest in the range $(0, 1)$:

valuesforu = solutions /@ Range[0, 1, 0.1]

(* Out: 
{{1., 0.}, {0.931991, 0.0426269}, {0.902059, 0.0618784}, {0.889307, 0.071569}, 
 {0.884889, 0.0771448}, {0.884867, 0.0808241}, {0.887377, 0.0835529}, {0.891474, 0.0857601}, 
 {0.896641, 0.0876553}, {0.902577, 0.0893498}, {0.909092, 0.0909076}}
*)

Finally, you seem to be interested in the maximum of the function 1 - x1[1] +x2[1], so we can calculate values of this function and separately find the highest one as follows:

1 - #1 + #2 & @@@ valuesforu
Max[%]

(* Out: {0., 0.110636, 0.15982, 0.182262, 0.192255, 0.195957, 0.196176, 0.194287, 
         0.191014, 0.186773, 0.181815} *)

(* Out: 0.196176 *)
$\endgroup$
2
0
$\begingroup$

Try this:

wynik1 = 0;
For[u = 0, u <= 1, u = u + 0.1,
 s = NDSolve[{x1'[t] == u*(10*x2[t] - x1[t]), x1[0] == 1, 
    x2'[t] == u*(x1[t] - 10*x2[t]) - (1 - u)*x2[t], x2[0] == 0}, {x1, 
    x2}, {t, 0, 1}];
 wynik = First[1 - x1[1] + x2[1] /. s];
 (*Print[wynik];*)
 If[wynik > wynik1, wynik1 = wynik; Print[wynik1]];
 ]
wynik1
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.