Given any nxn matrix of real coefficients A, we can define a bilinear form b A : R n x R n β R by
b A (x, y) = x T Ay,
and a quadratic form q A : R n β R by
q A (x) = b A (x, x) = x T Ax.
(For most common applications of quadratic forms q A, the matrix A is symmetric or even symmetric, positive definite, so feel free to assume that either one of them takes place if it matters to your answer.)
(In addition, FWIW, b I and q I (where I is the identity matrix nxn) are the standard scalar product and the square of the L 2 -norm on R n, i.e., X T y and x T x, respectively.)
Now suppose that I have two nxm matrices: X and Y and an nxn-matrix A. I would like to optimize the calculation as b A (x , i , y , i ) and q A (x , i ) (where x , i and y , i denote the ith column of X and Y, respectively), and I assume that, at least in some environments like numpy, R or Matlab, this will be associated with some form of vectorization.
The only solution I can think of is to create diagonal block matrices [X], [Y] and [A] with dimensions mn xm, mn xm and mn x mn respectively and with (block) diagonal elements x , i , y , i and A, respectively. Then the required calculations would be matrix multiplications [X] T [A] [Y] and [X] T [A] [X]. This strategy is most definitely not capable, but if there is a way to do it that is effective in terms of time and space, I would like to see it. (It goes without saying that any implementation that does not use the sparseness of these matrix matrices would be doomed.)
Is there a better approach?
My system preference for this is numpy, but the answers in terms of some other system that supports efficient matrix calculations such as R or Matlab may also be okay (provided I can figure out how to port them to numpy) .
Thanks!
<sub> Of course, computing the products X T AY and X T AX would compute the desired b A (x , i , y , i ) and q A (x , i ) (as the diagonal elements of the resulting mxm matrices) , along with the O (m 2 ) irrelevant b A (x , i , y , j ) and b A (x , i , x , j ), (for i β j), so this is a non-starter.