I wanted to know, how to evaluate multiple statements in a function in Mathematica.
E.g.
f[x_]:=x=x+5 and then return x^2
I know this much can be modified as (x+5)^2
but originally I wanted to read data from the file in the function and print the result after doing some data manipulation.
If you want to group several commands and output the last use the semicolon (;) between them, like
f[y_]:=(x=y+5;x^2)
Just don't use a ; for the last statement.
If your set of commands grows bigger you might want to use scoping structures like Module or Block.
You are looking for CompoundExpression
(short form ;
):
f[x_]:= (thing = x+5 ; thing^2)
The parentheses are necessary due to the very low precedence of ;
.
As Szabolcs called me on, you cannot write:
f[x_]:= (x = x+5 ; x^2)
See this answer for an explanation and alternatives.
Leonid, who you should listen to, says that thing
should be localized. I didn't do this above because I wanted to emphasize CompoundExpression
as a specific fit for your "and then" construct. As it is written, this will affect the global value of thing
which may or may not be what you actually want to do. If it is not, see both the answer linked above, and also:
Several people have mentioned already that you can use CompoundExpression
:
f[x_] := (y=x+5; y^2)
However, if you use the same variable x
in the expression as in the argument,
f[x_] := (x=x+5; x^2)
then you'll get errors when evaluating the function with a number. This is because :=
essentially defines a replacement of the pattern variables from the lhs, i.e. f[1]
evaluates to the (incorrect) (1 = 1+5; 1^2)
.
So, as Sjoerd said, use Module
(or Block
sometimes, but this one has caveats!) to localize a function-variable:
f[x_] := Module[{y}, y=x+5; y^2]
Finally, if you need a function that modified its arguments, then you can set the attribute HoldAll
:
Clear[addFive]
SetAttributes[addFive, HoldAll]
addFive[x_] := (x=x+5)
Then use it as
a = 3;
addFive[a]
a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With