Search code examples
matlabmatrixvectorizationmatlab-deployment

Alternative to diag(X'*C*X) in matlab


Consider an N x 1 vector x and an N x N matrix C. I would like to evaluate

 s = x'*C*x;

in matlab for many sampled of the vector x, e.g. consider M samples of x as an N x M matrix X; this can be done using

S = diag(X'*C*X);

but this is a poor solution as an M x M matrix is allocated in the process, and this breaks for M>1e5. Is there some matlab functionality which can suggest an alternative?


Solution

  • Perform the right matrix multiplication C*X, and then perform elementwise products, so that no unneeded operations are done:

    S = sum(X.*(C*X),1)';
    

    If your matrices are complex valued, you also need to conjugate:

    S = sum(conj(X).*(C*X),1).';