Borrar filtros
Borrar filtros

Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

What is an efficient way to create a sparse matrix from a set of data?

1 visualización (últimos 30 días)
Ehsan na
Ehsan na el 22 de Jun. de 2016
Cerrada: MATLAB Answer Bot el 20 de Ag. de 2021
Hey,
Consider following matrix:
x1 y1
x1 y2
x1 y3
x2 y1
x2 y4
x3 y5
I need to convert this matrix to a sparse matrix, i.e. all elements are zero except the element denoted at row xi and column yj. For this example the spars matrix will be as below:
y1 y2 y3 y4 y5
------------------------
x1| 1 1 1 0 0
x2| 1 0 0 1 0
x3| 0 0 0 0 1
The number of rows and columns are in order of several hundred thousands, hence the matrix is huge. The matrix only contains values 0 or 1.
What is an efficient algorithm to create this matrix?
Thanks

Respuestas (1)

Matt J
Matt J el 22 de Jun. de 2016
Editada: Matt J el 22 de Jun. de 2016
A=sparse(I,J,1);
Although, if the non-zero entries I,J are 0 and 1, you can save significant memory if you make the matrix type logical instead of type double,
A=sparse(I,J,true);
  1 comentario
John D'Errico
John D'Errico el 22 de Jun. de 2016
I would want to add that if your matrix is roughly 50% 0 and 1 as is shown, then it is not really sparse. In fact, it may take as much (or more) memory to create as sparse in that case.
So use sparse storage when you can. But remember that a sparse matrix needs to be truly sparse to be a gain. For example...
A = rand(1000) > 0.5;
B = sparse(A);
whos
Name Size Bytes Class Attributes
A 1000x1000 1000000 logical
B 1000x1000 4511329 logical sparse
So, A is a full logical matrix, with 50% zeros. B is the sparse form of that matrix. In fact, the sparse logical form in B requires 4.5 times as much memory to store!

La pregunta está cerrada.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by