2
$\begingroup$

This question already has an answer here:

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:

systemfunction[1,1,1]

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

$\endgroup$

marked as duplicate by Mr.Wizard functions Nov 13 at 13:38

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2
$\begingroup$

You can use

systemFunction[x_, y_, z_] = system

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

$\endgroup$
2
$\begingroup$

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.

$\endgroup$

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