Matlab allocates a sparse matrix more memory than is required

萝らか妹 提交于 2019-12-04 18:34:58

The memory storage format of a sparse matrix in MATLAB is a dense array of column pointers. Each column pointer points to a list of nonzero elements, and each element needs an index and a value. So the formula is

(max column num) x P + (num nonzero) x (P + S)

where P is pointer size (8 bytes on a 64-bit system, 4 on a 32-bit system), and S is the size of a single element. 1 for logical. For your problem I get 1275108, or "close enough".

So what to do about it? Note the big memory driver: maximum column number, due to the dense array of column pointers. In your case, if you reverse the index order and store the transpose of the matrix, it takes only 236 bytes (on your 32-bit system).

I do not know why this happens but I do know how to fix it. Here is some code revealing that a sparse matrix is linearly dependent on the number of columns.

for k = 1:6
  n = 10^k; 
  a = sparse(n, 100); % keep number of columns constant
  tmp = whos('a'); 
  fprintf('%1.0f bytes used\n', tmp.bytes); 
end

which produces

416 bytes used
416 bytes used
416 bytes used
416 bytes used
416 bytes used
416 bytes used

while keeping the number of rows constant with a = sparse(n, 100); instead gives

     56 bytes used
    416 bytes used
   4016 bytes used
  40016 bytes used
 400016 bytes used
4000016 bytes used

thus to optimize your code change s from a 34 x 318752 to a 318752 x 34 matrix by swapping the first two inputs of sparse.

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