问题
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.
回答1:
You could use
bsxfun. This gives the same result asA./(v'*w)without generating the matrixv.'*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 generatingv.'*w. If you need the sparse matrixA./(v'*w)(instead if the column vector of its nonzero values), usesparse(ii,jj,Anz./v(ii)'./w(jj).').
来源:https://stackoverflow.com/questions/19735356/doesnt-matlab-optimize-the-following