Matlab: a smart way to create a sparse matrix

I need to create a Matlab matrix, which is much larger than my physical memory, and I want to take advantage of the resolution.

This matrix is ​​really very sparse (say, N elements in the NxN matrix), and my ram is enough for this. I create a matrix as follows:

A = sparse (zeros (N));

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

+3
source share
3 answers

zeros(N)creates an NxN matrix that is not sparse, so you run out of memory. Your code is equivalent

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

Just do it sparse(N,N).

+8
source

, matlab. , - :

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

. , , . ,

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

I would recommend the full sparse syntax ([], [], [], N, N, N).

It is useful to redistribute if you know the maximum number of nonzero elements, since otherwise you will get reallocs when inserting new elements.

+3
source

All Articles