[localhost:~]$ cat * > /dev/ragfield

Tuesday, March 17, 2009

Call by reference in Mathematica

Parameters values passed into Mathematica functions are immutable. However, one can fake "call by reference" behavior in Mathematica by giving the function a Hold* (HoldAll/HoldFirst/HoldRest) attribute. That way the function can directly modify the variable passed to it.

Attributes[MyFunc] = HoldAll;
MyFunc[a_Symbol]:=(a[[2]] = 2.2);
b = {1., 2., 3., 4.}
{1.`, 2.`, 3.`, 4.`}
MyFunc[b];
b
{1.`, 2.2`, 3.`, 4.`}

Download Mathematica notebook

The drawback to doing this is that you have to pass a variable into the function. Passing a literal value will not work.

3 comments:

Anonymous said...

Great tip, thanks. swgreen at mit

Anonymous said...

Thank! Awesome post!

Anonymous said...

many thanks!!!!!!!!!

nice post : )