0
$\begingroup$
sol1[t_?NumericQ] := FindRoot[{a + b - t == 0, a - b - 1 == 0}, 
   {{a, 0.80, 0.95}, {b, 0.95, 2}}];

a0[t_] := sol1[t][[1, 2]]; 
b0[t_] := sol1[t][[2, 2]];
f[t_] := 5 + a0[t] - b0[t]^2;

Print[sol1[1][[1, 2]]];

max0 := NMaximize[f[t], t];
Print[max0];

max1 := FindMaximum[f[t], {t, 2}];
Print[max1];

Plot[f[t], {t, 0, 5}]
$\endgroup$
3
  • 1
    $\begingroup$ You don't really need FindRoot[] for a linear equation, y'know. $\endgroup$ Commented Feb 21, 2016 at 18:24
  • $\begingroup$ Your code is somewhat unclear and it should be possible to simplify it considerably. Why don't you tell us what you are trying to accomplish instead? $\endgroup$
    – MarcoB
    Commented Feb 21, 2016 at 18:26
  • $\begingroup$ Related, possibly duplicate: (14645), (21662), (34554), (63407) $\endgroup$
    – Mr.Wizard
    Commented Feb 21, 2016 at 18:33

2 Answers 2

1
$\begingroup$

By defining sol1[t_?NumericQ] := you will cause a symbolic argument to be held:

sol1[foo]    (* out:   sol1[foo]   *)

You can therefore not extract parts from it that do not exist. You should therefore make functions that call sol1 also hold symbolic arguments:

ClearAll[a0, b0]

a0[t_?NumericQ] := sol1[t][[1, 2]];
b0[t_?NumericQ] := sol1[t][[2, 2]];

Now symbolic arguments do not evaluate, but numeric ones do:

a0[foo]
a0[3.7]
a0[foo]

2.35
$\endgroup$
1
$\begingroup$

Consider the following rewrite of your code.

  1. Find a generic solution to your system of linear equations:

    solution = Solve[{a + b - t == 0, a - b - 1 == 0}, {a, b}]
    (* Out: {{a -> (1 + t)/2, b -> 1/2 (-1 + t)}} *)
    
  2. Define a function involving those solutions; no need to define it with SetDelayed (:=) in this case. Simple Set (=) will do fine here.

    f[t_] = 5 + a - b^2 /. First@solution
    (* Out: 5 - 1/4 (-1 + t)^2 + (1 + t)/2 *)
    
  3. Obtain the value of $t$ for which the function $f$ achieves its maximum value. The calculation can be done symbolically:

    maximum = ArgMax[f[t], t]
    (* Out: 2 *)
    
  4. Plot the function f and the position of the maximum to check:

    Plot[f[t], {t, 0, 5}, 
      Epilog -> {PointSize[0.02], Red, Point[{maximum, f[maximum]}]}
    ]
    

Mathematica graphics

$\endgroup$
1
  • $\begingroup$ Thanks for the help. This example represents a much bigger (non-linear) program, and was only meant to show the problem (getting the error messages). Please focus solely on this issue, and not on rectifying the code which is irrelevant per-se! $\endgroup$ Commented Feb 23, 2016 at 7:00

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.