# Create matrix from combinational arrangement of vectors

I am just trying to produce a short hand code which shall do the following:

I have a function of 2 vectors $f(\vec{v_1},\vec{v_2})$

f=#1^2+#2^2-#3-#4&;


and vectors $\vec{v_1},\vec{v_2}$ of the shape

v1={1,2};
v2={2,3};


as well as weights $w_1, w_2$

w1=1/4;
w2=3/4;


and I need to calculate the sum of all sets of possible combinations

w1*w1*f@@v1~Join~v1 + w1*w2*f@@v1~Join~v2 + w2*w1*f@@v2~Join~v1 + w2*w2*f@@v2~Join~v2


Is there a short hand notation for this? Like creating a matrix from all combinations of {v1,v2} and apply that matrix to the function?

In my real function I have 3d vectors instead of 2d vectors and there are 20 vectors instead of 2. I obviously don't want to write down all combinations by hand.

• Looks like a job for Outer... – Henrik Schumacher Feb 6 '18 at 10:22

Total[
Times[
KroneckerProduct[{w1, w2}, {w1, w2}],
Outer[
{x, y} \[Function] F @@ Join[x, y],
{v1, v2},
{v1, v2},
1
]
],
2]


1/16 F[1, 2, 1, 2] + 3/16 F[1, 2, 2, 3] + 3/16 F[2, 3, 1, 2] + 9/16 F[2, 3, 2, 3]

And for your final application, this might go well:

n = 20;
vectors = RandomReal[{-1, 1}, {20, 3}];
weights = RandomReal[{0, 1}, n];
Total[
Times[
KroneckerProduct[weights, weights],
Outer[{x, y} \[Function] F @@ Join[x, y], vectors, vectors, 1]
],
2]


If you define F such with only two vector arguments (and access the components in the body by [[ ... ]]) then simply

Total[KroneckerProduct[weights, weights], Outer[F, vectors, vectors, 1]], 2]


will also do.

As mentioned by @Henrik Schumacher the "outer"-solution is

{W1, W2}.Outer[F[##] &, {V1, V2}, {V1, V2}].{W1, W2}
(*W1^2 F[V1, V1] + W1 W2 F[V1, V2] + W1 W2 F[V2, V1] + W2^2 F[V2, V2] *)
`