# How do I create an array by applying a function to the index of each element?

I am looking for something like matrix(m, n, f), but for Mathematica rather than MuPAD, and for arrays rather than matrices. That is, I'm looking for a(n efficient) way of doing this without for-loops:

ret = zeros(m, n);
for i = 1:m
for j = 1:n
ret(i, j) = some_function([i, j]);
end
end


## 1 Answer

Couple of ways:

f[x_, y_] := y*x^2

SparseArray[{i_, j_} :> f[i, j], {3, 3}] // Normal

Array[f, {3, 3}]

Table[f[x, y], {x, 3}, {y, 3}]

(*
{{1, 2, 3}, {4, 8, 12}, {9, 18, 27}}

{{1, 2, 3}, {4, 8, 12}, {9, 18, 27}}

{{1, 2, 3}, {4, 8, 12}, {9, 18, 27}}


*)

If you already have the array (say in this example a 3x3 zeroes) and you want to go over it and apply some function based on indices (and perhaps existing values):

array = ConstantArray[0, {3, 3}];

(* example fn, takes current value and index *)
f[curval_, idx_] := curval + Total@idx

MapIndexed[f[#, #2] &, array, {2}]

(* {{2, 3, 4}, {3, 4, 5}, {4, 5, 6}} *)

• Well covered. +1 – Mr.Wizard Apr 20 '15 at 1:32