pythonnumpy

Create Matrix by Multiplying ith and jth Vector-Element in Numpy


I need to calculate a the error function V

V = Σi Σj X[i] X[j] σ[i][j]

Where σ[i][j] is a given matrix and I need a relatively fast solution. To do this I want to create another matrix Y where

Y[i][j] = X[i]*X[j]

So I that I can simply sum over Y * σ. Is there a good way to implement this with numpy functions?

So far I have tried to meshgrid(X, X) and then apply np.prod to each row, however this did yield the expected output and would have required a for-loop in python.

Edit: Minimal reproducable example:

cov = np.array(((0.1, 0.05), (0.05, 0.25)))
x = np.array((0.6, 0.4)

desired = x[0]*x[0]*cov[0][0] + x[0]*x[1]*cov[0][1] + x[1]*x[0]*cov[1][0] + x[1]*x[1] * cov[1][1]

Solution

  • np.dot supports matrix multiplication.

    Simply do

    np.dot(x,sigma).dot(x)