# How to turn a ruled pattern into a multivariable function [duplicate]

Fix m=2. My code generates a pattern like this one (n=2):

15 (x[1][1] y[1][1] + x[1][2] y[1][2]) + x[2][1] y[2][1] +
x[2][2] y[2][2] - 3 (x[1][1] y[2][1] + x[1][2] y[2][2])


For the case n=2, the pattern contains (x[1][i]y[1][j]+x[2][i]y[2][j]) for all $i,j=1,2$. Some of these parcels can have null coefficient, in this case they don't appear. It happened for (x[2][1] y[1][1] + x[2][2] y[1][2]) in the example above. Another example is the following (n=3):

-7 (x[1][1] y[1][1] + x[1][2] y[1][2]) +
3 (x[3][1] y[2][1] + x[3][2] y[2][2]) -
6 (x[1][1] y[3][1] + x[1][2] y[3][2])


Here, the pattern contains (x[1][i]y[1][j]+x[2][i]y[2][j]) for all $i,j=1,3$, but some of them had null coefficient.

In general, the pattern contains (x[1][i]y[1][j]+x[2][i]y[2][j]) for all $i,j=1,n$.

I would like to turn these patterns into a multivariable function, following the style of its output (x[i][j] or y[i][j]). The function have to be, for the case n=2, like

T[x[1][1]_,x[1][2]_,x[2][1]_,x[2][2]_,y[1][1]_,y[1][2]_,y[2][1]_,y[2][2]_]= *pattern*


($T$ takes a list like $(x_1, ..., x_n, y_1,..., y_n)$, with $x_i, y_j\in\Bbb R^2$ and rerurns a real number)

In general, given m and n, I already have a code that genegates a sum containing parcels of the type (x[1][i]y[1][j]+...+x[n][i]y[n][j]), $i,j=1,...,m$. I am looking for a code that do three things: (1) makes a function having x[i][j] and y[i][j] as variables; (2) works with any value of m and n fixed; and (3) takes them in order, something like this:

T[x[1][1]_,...,x[1][m]_,...,x[n][1]_,...,x[n][m]_,y[1][1]_,...,y[1][m]_,...,y[n][1]_,...,y[n][m]__]= *pattern*


P.s.: I have to be able to apply Lagrange Multipliers with the function (adding $2n$ constraints).

This is basically a duplicate of Define function from expression. This time I will provide a function to do the conversion. Here is the function:

toFunc[expr_, h_]:=h[X_, Y_]:=Block[{x,y},
x[i_][j_]:=X[[i,j]];
y[i_][j_]:=Y[[i,j]];
expr
]


Here is one of your expressions:

expr = 15 (x[1][1] y[1][1] + x[1][2] y[1][2]) + x[2][1] y[2][1] +
x[2][2] y[2][2] - 3 (x[1][1] y[2][1] + x[1][2] y[2][2]);


Using toFunc:

toFunc[expr, T]


Check:

T[{{x11, x12},{x21,x22}}, {{y11, y12}, {y21,y22}}]


15 (x11 y11 + x12 y12) + x21 y21 + x22 y22 - 3 (x11 y21 + x12 y22)