Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematica, nested optimization

I want to use the solution of Maximization, defined as a function, in another function. Here's an example:

f1[y_] := x /. Last[Maximize[{Sin[x y], Abs[x] <= y}, x]]  (* or any other function *)

This definition is fine, for example if I give f1[4], I get answer -((3 \[Pi])/8).

The problem is that when I want to use it in another function I get error. For example:

FindRoot[f1[y] == Pi/4, {y, 1}]

Gives me the following error:

ReplaceAll::reps: {x} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>

FindRoot::nlnum: The function value {-0.785398+(x/.x)} is not a list of numbers with dimensions {1} at {y} = {1.}. >>

I've been struggling with this for several days now! Any comment, idea, help, ... is deeply appreciated! Thank you very much!

like image 318
user2122036 Avatar asked Mar 01 '13 03:03

user2122036


1 Answers

When y is not a number, your Maximize cannot be resolved, in which case the Last element of it is x, which is why you get that odd error message. You can resolve this by clearing the bad definition of f1 and making a new one that ensures only numeric arguments are evaluated:

ClearAll[f1]
f1[y_?NumericQ] := x /. Last[Maximize[{Sin[x y], Abs[x] <= y}, x]]

FindRoot[f1[y] == \[Pi]/4, {y, 1}]
(* {y -> 0.785398} *)
like image 68
Xerxes Avatar answered Oct 12 '22 10:10

Xerxes