Replace diagonals in a matrix
9 views (last 30 days)
Show older comments
Hello every one,
How to replace the upper and lower part of a n*n matrix with zeros (The upper part starts from "diagonal+2" until n while the lower part starts from "diagonal-2" until n)?
1 Comment
Image Analyst
on 23 Jan 2021
Original question is below in case he deletes it like he's done before:
Replace diagonals in a matrix
Hello every one,
How to replace the upper and lower part of a n*n matrix with zeros (The upper part starts from "diagonal+2" until n while the lower part starts from "diagonal-2" until n)?
Accepted Answer
More Answers (1)
David Goodmanson
on 19 Jan 2021
Edited: David Goodmanson
on 19 Jan 2021
Hi Hasan,
here is one way
r = rand(7,7)
n = size(r,1);
m = (n-1)/2;
a = (-m:m)-(-m:m)';
r(abs(a)>1)=0
assuming the main diagonal is number 0, and the zeros start on the +-2nd diagonal, otherwise adjust the '1' on the last line of code accordingly
See Also
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!