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.`}
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:
Great tip, thanks. swgreen at mit
Thank! Awesome post!
many thanks!!!!!!!!!
nice post : )
Post a Comment