I have a huge matrix to A to solve for Ax=B. There are some rows with zero elements in A and I want to modify the diagonal for these rows. So how can I fast find these rows with all zero elements? for loop is rather slow.

2 views (last 30 days)
I have a huge matrix to A to solve for Ax=B. There are some rows with zero elements in A and I want to modify the diagonal for these rows. So how can I fast find these rows with all zero elements? for loop is rather slow.

Answers (2)

KSSV
KSSV on 13 Mar 2019
Edited: KSSV on 13 Mar 2019
A = [0 0 0 ; 1 2 3; 4 5 6] ;
idx = sum(A,2)==0
A(idx,:)
Or Simply:
A = [0 0 0 ; 1 2 3; 4 5 6] ;
idx = any(A,2)
A(idx,:)

Andrei Bobrov
Andrei Bobrov on 13 Mar 2019
Edited: Andrei Bobrov on 13 Mar 2019
"How to set diagonal as 1 for the row with all zero elements?"
A = A + diag(~diag(A));
or
n = all(A==0,2);
A = A + diag(n);
or
n = all(A==0,2);
ex = (1:size(A,1)+1:numel(A))';
A(ex) = A(ex) + n;

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!