Suppose I have the following expression

system = x + y + z

And I would like to define a function that contains this function, without explicitly typing the right hand side of the above equation.

I tried:

systemfunction = Function[{x,y,z},system]

but this does not produce the desired result as the following evaluation yields:


(x + y + z)[1,1,1]


You can use

systemFunction[x_, y_, z_] = system

Note the use of = instead of := and see What is the difference between Set and SetDelayed?


The problem you face here is that Function does not evaluate your system variable. It takes it as it is without making the transformation of system -> x+y+z. You can see this in the output directly:

Function[{x, y, z}, system]
(* Function[{x, y, z}, system] *)

This comes from how Function treats its arguments. You can prevent this by temporary using another function (here List) which doesn't make this and then replacing the List with Functions:

system = x + y + z;
systemFunction = Function @@ {{x, y, z}, system}

Now systemFunction[1, 1, 1] gives 3 as expected.

Please note, that this is only one (and not the best) way to do it. To understand how all this works in Mathematica you should read about Attributes, HoldAll and injecting code. If you don't find anything searching this site, I'm sure we can collect some useful links.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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