How can I speed up assignments to sparse matrices in MATLAB?

조회 수: 31(최근 30일)
MathWorks Support Team 2009년 6월 27일
편집: Yokesh 2019년 4월 20일
How can I speed up assignments to sparse matrices in MATLAB?
I am assigning values to a sparse matrix which I have already created. However, this seems to be very slow. Is there a way to make this process faster?

채택된 답변

MathWorks Support Team 2009년 6월 27일
Here are two suggestions for speeding up the assignment of values to sparse matrices:
1) Using SPALLOC, specify the number of nonzero elements that the sparse matrix will have. This will allow you to specify how much space should be allocated. If you know that you will be assigning new values, you can specify more space than you initially use. This way, MATLAB will not need to reallocate extra memory later.
2) If you are creating a sparse vector, use a column vector instead of a row vector. MATLAB needs to keep track of every column of the sparse matrix, so if you use a column vector instead of a row vector, then it will only need to keep track of a single column, which will save memory and processing time.

댓글을 달려면 로그인하십시오.

추가 답변(1개)

Yokesh 2019년 4월 20일
편집: Yokesh 2019년 4월 20일
% Creating elements for a sparse matrix
% We need to create a column vector for each i,j,v
% where A(i,j) = v
i = randi(100,100,1);
j = randi(100,100,1);
v = rand(100,1);
A = sparse(i, j, v);
% Another method: Let's say you have your i,j,v
% column vectors as a (:,3) matrix
temp = [i j k];
A = sparse(temp(:,1), temp(:,2), temp(:,3));
% Warning: A = sparse(temp) is not a wise method

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by