How do you make the diagonal and certain off-diagonal elements of a matrix zero?
73 views (last 30 days)
Show older comments
L'O.G.
on 14 Feb 2023
Commented: Walter Roberson
on 14 Feb 2023
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 Comments
Accepted Answer
Walter Roberson
on 14 Feb 2023
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.
2 Comments
Walter Roberson
on 14 Feb 2023
n = 9;
A = rand(n)
newA = full(spdiags(zeros(9,3), -1:1, A))
More Answers (1)
Torsten
on 14 Feb 2023
Edited: Torsten
on 14 Feb 2023
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 Comment
Walter Roberson
on 14 Feb 2023
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
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!