I would like to define a function which produces an $N\times N$ matrix where each element is a function of the input values ($N$ is a fixed constant). However, each element of the function needs to be computed from a predefined list of values.
In the specific example I am working on, I have a two lists, A
and B
: A
contains the $(i,j)$ matrix indices and B
contains vectors $\vec{v}$ corresponding to those matrix indeces (in the same order) For this example my vectors are three dimensional. However in the first list some indices are repeated more than once. Consider if I have some function $g(\vec{r}\cdot\vec{v})$, and I want to define a matrix $f_{ij}(\vec{r})$ such that each element is the sum of $g(\vec{r}\cdot\vec{v})$ for each $\vec{v}$ which corresponds to the index $(i,j)$.
I could make a matrix by simply defining an empty matrix of zeroes and looping over the list index,
f = ConstantArray[0, {N, N}]
For[i = 1, i <= Length[A], i++,
f[[ A[[i, 1]], A[[i, 2]] ]] += g[B[[i]].{x,y,0}]
]`
But I can't do this if f
is a function
f[x_,y_] := ConstantArray[0, {N, N}]
For[i = 1, i <= Length[A], i++,
f[[ A[[i, 1]], A[[i, 2]] ]] += g[B[[i]].{x,y,0}]]
]`
I'm sure there's better ways but I just wanted to give a basic example of how I was thinking of approaching it. For now I built the matrix for the first way, printed it out in MatrixForm
, copied and defined f[x_,y_] =
and pasted the entire matrix. This is obviously not ideal, especially for larger matrices.
f[x_] := ...
and notf[x_] = ...
. When you definef[x_,y_] := ...
, you do not need to use double brackets asf[[ a1, a2 ]]
to use it.f[[ a1, a2 ]]
means the a2th element of a1th row of the matrix f. $\endgroup$:=
and clarified the code slightly. In the first examplef
is just a matrix and I am referencing its elements. In the second example (which is pseudocode),f
is a function which returns a matrix, and I want to apply the same logic:f[[i,j]]
(pseudocode: the{i,j}
element of the matrix returned byf[x_,y_]
) is the sum of allg[B[[n]].{x,y,0}]
such thatA[[n]] = {i,j}
. $\endgroup$