开发者

Matlab: a smart way to create a sparse matrix

I have to create a matlab matrix that is much bigger that my phisical memory, and i want to take advantage of the sparsity.

This matrix is really really sparse [say N elements in an NxN matrix], and my ram is enought for this. I create the matrix in this way:

A开发者_如何学C=sparse(zeros(N));

but it goes out of memory. Do you know the right way to create this matrix?


zeros(N) is creating an NxN matrix, which is not sparse, hence you are running out of memory. Your code is equivalent to

temp = zeros(N)
A = sparse(temp)

Just do sparse(N,N).


Creating an all zeros sparse matrix, and then modifying it is extremely inefficient in matlab. Instead of doing something like:

   A = sparse(N,N)  % or even A = sparse([],[],[],N,N,N) 
   A(1:N,7) = 1:N

It is much more efficient to construct the matrix in triplet form. That is, construct the column and row indices and the nonzero entries first, then form the matrix. For example,

   i = 1:N;
   j = 7*ones(1,N); 
   x = 1:N;
   A = sparse(i,j,x,N,N);


I'd actually recommend the full syntax of sparse([],[],[],N,N,N).

It's useful to preallocate if you know the maximum number of nonzero elements as otherwise you'll get reallocs when you insert new elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜