set efficently specific rows in a sparse matrix to 0

조회 수: 7 (최근 30일)
Marko
Marko 2021년 9월 3일
댓글: Walter Roberson 2021년 9월 3일
Hello comunity,
I have a sparse matrix J and i want to set specific rows to 0.
My code's like this:
J = sparse(blkdiag(rand(1000,1000),rand(100,100),rand(200,200))); % just for example
vec = [1:10,20:400,800:1100]'; % just for example
J(vec,:) = 0;
Is there a faster way how to set the specific lines of J to 0?
best regards,
Marko

채택된 답변

Walter Roberson
Walter Roberson 2021년 9월 3일
Would it be practical in your situation to transpose the matrix, so that you were setting columns to 0 instead of rows? With the implementation of sparse(), it is more efficient to change multiple items in one column.
Beyond that: the usual efficiency hint is to find() the non-zero objects of interest, and then use those indices to assign new values.
It would be interesting to benchmark,
J(vec,:) = 0;
compared to
[r,c] = find(J(vec,:));
J(sub2ind(size(J), vec(r), c)) = 0;
compared to
[r,c,s] = find(J(vec,:));
J = J - sparse(vec(r), c, s, size(J,1), size(J,2));
The third of those is locating the non-zero elements of those rows of J, along with the values there, and building a new sparse array that contains only those elements, and then subtracts the two.

추가 답변 (1개)

Marko
Marko 2021년 9월 3일
here are the benchmark results:
ver Var2
___ _____
1 2.242
2 NaN
3 0.87
for version 2 i get the error:
Error using sub2ind (line 51)
The subscript vectors must all be of the same size.
Error in setBC (line 12)
J(sub2ind(size(L), vec(r), c)) = 0;
so your code snippet (version 3) saved me 61% or 1,3s every time i ran a computation.
Thank you very much
  댓글 수: 1
Walter Roberson
Walter Roberson 2021년 9월 3일
In your posted question, vec is a column vector. And the code I posted works when vec is a column vector. But if vec were a row vector instead then you would get the error you mention.

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

카테고리

Help CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by