Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

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

조회 수: 2 (최근 30일)
Ehsan na
Ehsan na 2016년 6월 22일
마감: MATLAB Answer Bot 2021년 8월 20일
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

답변 (1개)

Matt J
Matt J 2016년 6월 22일
편집: Matt J 2016년 6월 22일
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
John D'Errico
John D'Errico 2016년 6월 22일
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!

이 질문은 마감되었습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by