How do you make the diagonal and certain off-diagonal elements of a matrix zero?
古いコメントを表示
I have a square matrix and would like to make the diagonal elements zero, as well as select elements that are off-diagonal. For the latter, I only want the elements next to (one removed from) the diagonal to be zero, e.g., I would want A(5,6) and A(6,5) to be 0 for a matrix A. I can do the former part for the diagonal by
A_new = A - diag(diag(A));
But how do I do the part for the off-diagonal?
採用された回答
その他の回答 (1 件)
n = 9;
A = rand(n)
for i=1:n-1
A(i,i+1) = 0.0;
A(i+1,i) = 0.0;
end
A
1 件のコメント
The above can be vectorized. The vectorized version is faster than the loop or than my spdiags() solution.
The spdiags() solution is more compact, and so in some sense easier to understand. On the other hand, spdiags() is not one of the more common routines, so fewer people would be expected to understand it immediately without looking at the reference work; and while they might understand it for a while after that, if you were to have the same people look at the code (say) 6 months later, they would probably have lost the understanding. The loop solution is the more robust to that kind of longer term mental decay.
n = 9;
A = rand(n)
Acopy = A;
tic
for i=1:n-1
A(i,i) = 0.0;
A(i,i+1) = 0.0;
A(i+1,i) = 0.0;
end
toc
A
A = Acopy;
tic
n1 = n+1;
A(1:n1:end) = 0;
A(2:n1:end) = 0;
A(n1:n1:end) = 0;
toc
A
A = Acopy;
tic
A = full(spdiags(zeros(9,3), -1:1, A));
toc
A
カテゴリ
ヘルプ センター および File Exchange で Operating on Diagonal Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!