Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doesn't Matlab optimize the following?

I have a very long vector 1xr v, and a very long vector w 1xs, and a matrix A rxs, which is sparse (but very big in dimensions).

I was expecting the following to be optimized by Matlab so I won't run into trouble with memory:

 A./(v'*w)

but it seems like Matlab is actually trying to generate the full v'*w matrix, because I am running into out of memory issue. Is there a way to overcome this? Note that there is no need to calculate all v'*w because many values of A are 0.

EDIT: If that were possible, one way to do it would be to do A(find(A))./(v'*w)(find(A));

but you can't select a subset of a matrix (v'*w in this case) without first calculating it and putting it in a variable.

like image 281
kloop Avatar asked Nov 01 '13 21:11

kloop


1 Answers

  • You could use bsxfun. This gives the same result as A./(v'*w) without generating the matrix v.'*w:

    bsxfun(@rdivide, bsxfun(@rdivide, A, v'), w)
    
  • Another possibility: if you only want the nonzero values, use:

    [ii jj Anz] = find(A);
    Anz./v(ii)'./w(jj).'
    

    This gives a column vector corresponding to your A(find(A))./(v'*w)(find(A)), again without generating v.'*w. If you need the sparse matrix A./(v'*w) (instead if the column vector of its nonzero values), use sparse(ii,jj,Anz./v(ii)'./w(jj).').

like image 153
Luis Mendo Avatar answered Sep 20 '22 17:09

Luis Mendo