3
votes

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?

3

3 Answers

8
votes

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

5
votes

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);
3
votes

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.