3
$\begingroup$

I have a function that I want to generate a square matrix whose entries are run from 1,...,n and whose i,jth entry is f(i,j) for some function f. My code that I have right now is genMat[n_, f_[x_, y_]] := Table[f[i, j], {i, n}, {j, n}], but if I set f[x_,y_]:=x*y, then genMat[4,f[x,y]] evaluates to {{2, 3, 4, 5}, {3, 4, 5, 6}, {4, 5, 6, 7}, {5, 6, 7, 8}}, the matrix generated from adding the values together as opposed to multiplying them. It does this for all other n. Anybody know what is going on here? Thanks.

$\endgroup$
  • 3
    $\begingroup$ Something is weird... maybe you have old definitions lingering. I suggest restarting the kernel and trying again. $\endgroup$ – bill s Jul 14 at 0:56
  • $\begingroup$ Yeah, I retried it the next day and my method ended up working. Must’ve just been a weird bug $\endgroup$ – user3308874 Jul 16 at 17:00
5
$\begingroup$

Recommend that you look at Array

Clear["Global`*"]

genMat[n_Integer?Positive, f_] := Array[f, {n, n}]

genMat[4, f]

(* {{f[1, 1], f[1, 2], f[1, 3], f[1, 4]}, {f[2, 1], f[2, 2], f[2, 3], 
  f[2, 4]}, {f[3, 1], f[3, 2], f[3, 3], f[3, 4]}, {f[4, 1], f[4, 2], f[4, 3], 
  f[4, 4]}} *)

genMat[4, Times]

(* {{1, 2, 3, 4}, {2, 4, 6, 8}, {3, 6, 9, 12}, {4, 8, 12, 16}} *)

genMat[4, #1^2 - 3*#2 &]

(* {{-2, -5, -8, -11}, {1, -2, -5, -8}, {6, 3, 0, -3}, {13, 10, 7, 4}} *)
| improve this answer | |
$\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.