1

Question about assignments and variables

(* For example *) SP = SparseArray[{},5] or SP = Range[5]

now we want to work with this array in some another function :

(* example *) Fun[array_]:= array[[3]] = 100 ; (* set cell №3 equal to 100*)

then we eval

Fun[SP]

ERROR! output will be an Error like: Set::write Tag SparseArray in ... is Protected.

So what is the right way to change the arguments of function in function (non-pure-functions)? How to creare analog-like of Part[]?

maybe smth like:

Clear[f]; f[a_]:=Set[Symbol[a][[3]],100]; A =SparseArray[{},5]; f["A"]; 

But it's error again

Neysor
  • 3,893
  • 11
  • 34
  • 66
Jo Ja
  • 243
  • 4
  • 14
  • Welcome to StackExchange! there is a new StackExchange site dedicated to Mathematica which might be of interest to you. http://mathematica.stackexchange.com/ – magma Mar 25 '12 at 08:17
  • I am certain this is a duplicate question but I am feeling lazy. – Mr.Wizard Mar 30 '12 at 10:54

2 Answers2

2

I believe that Chris Degnen's method should generally be avoided.
Mathematica provides a better way: the Hold attributes.

a = Range[5];

SetAttributes[fun, HoldFirst]

fun[array_] := array[[3]] = 100

fun[a];

a
{1, 2, 100, 4, 5}

As a "pure function":

b = Range[5];

fun2 = Function[array, array[[3]] = 100, HoldFirst];

fun2[b];

b
{1, 2, 100, 4, 5}
Mr.Wizard
  • 24,179
  • 5
  • 44
  • 125
0

You can do it like this:

SP = Range[5];
Fun[array_] := array[[3]] = 100;(*set cell №3 equal to 100*)
Fun[Unevaluated@SP];
SP

{1, 2, 100, 4, 5}

Chris Degnen
  • 8,443
  • 2
  • 23
  • 40