How do you make the diagonal and certain off-diagonal elements of a matrix zero?
169 ビュー (過去 30 日間)
古いコメントを表示
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?
0 件のコメント
採用された回答
Walter Roberson
2023 年 2 月 14 日
S = spdiags(Bin,d,A) replaces the diagonals in A specified by d with the columns of Bin.
... after which you would full()
This could be used directly to replace diagonals -1:1 with zeros. Or you could use spdiags twice to extract multiple diagonals simultaneously and create a matrix with just those, and subtract from the original... the generalization of your current code.
その他の回答 (1 件)
Torsten
2023 年 2 月 14 日
編集済み: Torsten
2023 年 2 月 14 日
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 件のコメント
Walter Roberson
2023 年 2 月 14 日
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
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!