Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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? – J. M. 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? – J. M. Nov 9 '12 at 8:33
up vote 2 down vote accepted

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;
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


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


share|improve this answer
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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