# function on a multidimensional array in Mathematica

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?

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;
)


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: *)