2
$\begingroup$

Let's say I created a function that calculates something inside a module. How do I assign that result to a global value?

Let's say I have this:

function[input_]:=input*5;

findRoot[fun,input]:= module[{iterations=0}, While[iterations<10, result=fun[input]]; 
iterations = iterations + 1; input=input/2;
savetoglobal = result];

How do I save the result to the global environment? (sorry if this example doesn't make sense).

Any help would be greatly appreciated.

$\endgroup$
3
  • $\begingroup$ Simply return the value you want to save from your function, and then save that value to a global variable in the calling code outside the function. This is a generally considered safer because it avoids relying on side-effects. $\endgroup$
    – MarcoB
    Sep 28, 2022 at 15:22
  • $\begingroup$ @MarcoB How would that look? How do I save something after I have returned it? You mean if the result is 150.553, I will just manually write 150.553 and save that to a value? Problem is, I need to run findRoot with updated parameters based on this value many times (while I keep updating it). So it would be nice to be able to automate it a bit by saving that value to to a global value directly in the module. $\endgroup$ Sep 28, 2022 at 15:32
  • 1
    $\begingroup$ No, not by hand, but by assigning the result to a variable: result = findroot[...]. The result will contain the result of running findroot with the specific parameters you gave. $\endgroup$
    – MarcoB
    Sep 28, 2022 at 15:37

1 Answer 1

4
$\begingroup$

How do I save the result to the global environment?

If you assign a value inside a module to a variable which is not defined as local variable in the module, it is automatically put in global space.

ClearAll[x];
x
foo[z_] := Module[{n},
  n = 5;
  x = z + 10; (*update some global variable x *)
  Print["I am done"]
  ];
foo[3];

Now when you examine after the call $x$ it will exist in global space and have value 12.

Mathematica graphics

And it is global

Mathematica graphics

So you do not have to do anything. But it is not good programming practice to do this. Functions should only communicate with the outside world via input and explicit return value. They should not have any other side effects.

You can also notice, if you look closely, from the color of the symbol inside the module, that it is global

enter image description here

$\endgroup$
1
  • 1
    $\begingroup$ What I understand here is that only the values inside the brackets are stored locally only, but every new variable is stored globally. That information is super useful to me, thank you! $\endgroup$ Sep 28, 2022 at 15:35

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