Search code examples
pythonnumpycvxpy

Outer product in CVXPY


I have an objective function that depends on a sum of outer products. If I could use Numpy functions, I would write this as:

A = np.ones(m, n)
U = Variable(m, n)
objective = np.trace(sum([np.outer(A[i,:], U[i,:]) for i in range(m)]))

Of course np.outer doesn't work when U is a variable. Is there a cvxpy affine function that would implement this?


Solution

  • cvxpy has a kron function that works. Since it only works on 2d Variables and 2d-arrays, you have to reshape the vectors to (n, 1) vectors first:

    cvx.trace(sum([cvx.kron(A[i, :].reshape(n,1), cvx.reshape(U[i,:], (n,1))
                   for i in range(m)]))
    

    Another solution would be to simply write the matrix product:

    cvx.trace(sum([A[i, :].reshape(n, 1) @ cvx.reshape(U[i,:], (1, n)
                   for i in range(m)]))