# How do I numerically solve a custom function?

Whenever I use functions like FindRoot or NDSolve, it sends x through the function and deals with the result. That would be fine if I was sending a simple math function through, but I have something more like a short program. Is there any way to make it solve it by putting specific values through the function and looking at the results?

-
You can give a program as a function to FindRoot. Just be sure to restric the arguments to numerical values, e.g. programF[x_?NumberQ] := ...; FindRoot[programF[x]==0,{x,1}]. –  Daniel Lichtblau Nov 8 '12 at 22:41
What do I do about passing arrays? –  DanielLC Nov 9 '12 at 0:56
That's a bit vague. Could you maybe talk about your actual problem, so we can be more helpful? –  Guess who it is. Nov 9 '12 at 2:17
To pass array try programF[x_?(ArrayQ[#, _, NumericQ] &)] := ...; –  PlatoManiac Nov 9 '12 at 2:18
@Plato, like x_ /; ArrayQ[x, _, MatchQ[#, 0 | 1] &] then? –  Guess who it is. Nov 9 '12 at 8:33

I will give you a simple but realistic example. Imagine you are given two $d$-dimensional vectors $X$ and $B$. Now you are asked to find a matrix say $A$ such that $AX=B.$ How can we use Mathematica to solve this problem?

Prepare the two vectors X and B

d = 6;
SeedRandom[123];
X = RandomInteger[{1, 100}, d];
B = RandomReal[{200, 400}, d];


Now is time to define a function that takes a numerical $d\times d$-dimensional array $A$ as input and computes the norm $|A X-B|.$

Obj[A_?(ArrayQ[#, _, NumericQ] &)] := (A. X - B) // Norm;


At this point one would try to minimize the above function in order to get the matrix $A$ such that $AX=B$ holds approximately. We use the FindMinimum function with a derivative free method option.

FindMinimum[Obj[A], {A, RandomReal[{1, 25}, {d, d}]},
Method -> "PrincipalAxis", AccuracyGoal -> 12, PrecisionGoal -> 60,
MaxIterations -> 1000] // Short


{1.39237*10^-13,{A->{{-66.9631,20.7114,14.3336,11.7857,9.99711,14.8347},{-<<19>>,<<4>>,<<19>>},<<3>>,{<<1>>}}}}

Similar things can be done for functions like FindRoot or NDSolve. Hope this helps.

BR

-
This works, but when I tried to modify it to use a real number (replacing (ArrayQ[#, _, NumericQ] &) with NumberQ) or even a one dimensional array (I just changed the program so it uses one dimensional arrays and set the initial point to one) it started sending variables through again. Also, taking out the ?(ArrayQ[#, _, NumericQ] &) part also resulted in that. Am I modifying it wrong? I need to run these sorts of functions with a real number and a one dimensional array. –  DanielLC Nov 12 '12 at 23:44
Never mind. It seems to work fine now. –  DanielLC Nov 14 '12 at 23:17