Doesn't Matlab optimize the following?

我是研究僧i 提交于 2019-12-08 19:31:52

问题


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 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).').



来源:https://stackoverflow.com/questions/19735356/doesnt-matlab-optimize-the-following

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!