# 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 y + x y) + x y +
x y - 3 (x y + x y)


For the case n=2, the pattern contains (x[i]y[j]+x[i]y[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 y + x y) in the example above. Another example is the following (n=3):

-7 (x y + x y) +
3 (x y + x y) -
6 (x y + x y)


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

In general, the pattern contains (x[i]y[j]+x[i]y[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_,x_,x_,x_,y_,y_,y_,y_]= *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[i]y[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_,...,x[m]_,...,x[n]_,...,x[n][m]_,y_,...,y[m]_,...,y[n]_,...,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 y + x y) + x y +
x y - 3 (x y + x y);


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)