Info
此问题已关闭。 请重新打开它进行编辑或回答。
What is an efficient way to create a sparse matrix from a set of data?
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
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
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!