2
$\begingroup$

I'm new to Mathematica today. I would like to write a function that will implement the following pseudocode:

f[x_]:=
  Do something 
  return y

I have searched the documentation, but I'm still very confused. How do I return a variable after some complicated procedure? Use Return? It doesn't work sometimes.

$\endgroup$

closed as off-topic by Roman, Pinti, MarcoB, Daniel Lichtblau, Carl Lange Jun 7 at 7:13

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – Roman, Pinti, MarcoB, Daniel Lichtblau, Carl Lange
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    $\begingroup$ Don't use Return. Just have the result you want to return be the last thing in your function. $\endgroup$ – b3m2a1 Jun 6 at 1:45
  • 3
    $\begingroup$ You should probably read this. $\endgroup$ – Rohit Namjoshi Jun 6 at 1:48
2
$\begingroup$

You can do something like this (just a contrived example)

f[x_] := Module[{y},
   y = {1, x, x^2};
   Return[y]];

but the Return is not needed so you can do this

f[x_] := Module[{y},
   y = {1, x, x^2};
   y];

also and, in fact, you can simplify it to this

f[x_] := Module[{y},
   y = {1, x, x^2}];

or perhaps if you want to, even just this

f[x_] := {1, x, x^2};

but you will want to read the tutorials for more details.

For local variables you may want to read about the differences between Module, Block and With. Of course, you could also use global variables if you want to do so.

$\endgroup$
  • 1
    $\begingroup$ Why not just f[x_] = {1, x, x^2}? $\endgroup$ – Roman Jun 6 at 11:04
  • $\begingroup$ Looks cool! Why one has to use Module to localize all the variables inside a function (I mean, of course, this is a principle for functions)? Is there any other way to do this without Module? $\endgroup$ – Y.M.Zh Jun 6 at 14:21
  • $\begingroup$ And why not a pure function: f = {1, #, #^2} &; Then there is nothing to localize. $\endgroup$ – bill s Jun 9 at 13:46
  • $\begingroup$ @bills Perhaps it can be used in some cases, but "Do something; return y" is not specific. It could be very complicated code. $\endgroup$ – Somos Jun 9 at 14:05

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