3
$\begingroup$

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
$\endgroup$
6
$\begingroup$

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}} *)
$\endgroup$
  • $\begingroup$ Well covered. +1 $\endgroup$ – Mr.Wizard Apr 20 '15 at 1:32

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.