0
$\begingroup$

I have a 3 dimensional array S, elements of which are labelled by S[[x,y,z]]. I want to write a function f[S,x,y,z] that given a point {x,y,z} it applies

S[[x,y,z]]=1; S[[x+1,y,z]]=5; S[[x+1,y+1,z+1]]=9; 

How do I write this?

$\endgroup$
2
$\begingroup$

In order to enable call by reference, we have to give the HoldFirst (or HoldAll) attribute.

ClearAll[f];
SetAttributes[f, HoldFirst];
f[S_, x_, y_, z_] := (
  S[[x, y, z]] = 1; 
  S[[x + 1, y, z]] = 5; 
  S[[x + 1, y + 1, z + 1]] = 9;
)
$\endgroup$
0
$\begingroup$

If you really want to pass an array by name and have it implicitly changed, do as Henrik suggested. However, this implicitness is likely to get you into trouble at some point. So unless the cost to creating a new array is substantial, I suggest that you instead use ReplacePart.

data = ConstantArray[0, {3, 3, 3}];    (* fake data *)

f1[ar3d_, {x_, y_, z_}] := ReplacePart[ar3d, {
   {x, y, z} -> 1,
   {x + 1, y, z} -> 5,
   {x + 1, y + z, z + 1} -> 9
   }]

f1[data, {1, 1, 1}]  (* a new array! *)

f1a = f1[data, #] &; (* closure -> data is implicit *)

f1a[{1, 1, 1}]  (* a new array! *)

data   (* the data remain unchanged: *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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