简体   繁体   中英

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=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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM