MATLAB Answers

Replace diagonals in a matrix

33 views (last 30 days)
Hasan Hassoun
Hasan Hassoun on 19 Jan 2021
Commented: Image Analyst on 23 Jan 2021
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
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)?

Sign in to comment.

Accepted Answer

Matt J
Matt J on 19 Jan 2021
For example,
A=rand(10),
A = 10×10
0.3632 0.5683 0.2698 0.2133 0.4828 0.8948 0.0478 0.7711 0.5088 0.7301 0.8024 0.1100 0.1475 0.6313 0.8957 0.8629 0.1435 0.8356 0.1381 0.8203 0.8949 0.0767 0.3939 0.2073 0.3055 0.5721 0.7656 0.1443 0.3270 0.6013 0.5722 0.1502 0.8491 0.7124 0.9746 0.7291 0.9774 0.9558 0.4083 0.0934 0.1948 0.7491 0.7331 0.3686 0.4528 0.2436 0.2373 0.4254 0.9163 0.6997 0.4224 0.4079 0.6316 0.8894 0.8130 0.2013 0.0054 0.5217 0.1405 0.7939 0.0219 0.5942 0.3860 0.2447 0.6384 0.9649 0.3000 0.2048 0.2233 0.1450 0.4361 0.2666 0.2646 0.3323 0.6236 0.6866 0.9302 0.3413 0.4398 0.0531 0.3450 0.6491 0.0609 0.1894 0.8414 0.7489 0.1080 0.4159 0.2769 0.3304 0.0411 0.9652 0.9593 0.3298 0.9979 0.3895 0.2349 0.0686 0.9871 0.3078
mask=tril( triu( true(size(A)), -2 ), +2);
B=A.*mask
B = 10×10
0.3632 0.5683 0.2698 0 0 0 0 0 0 0 0.8024 0.1100 0.1475 0.6313 0 0 0 0 0 0 0.8949 0.0767 0.3939 0.2073 0.3055 0 0 0 0 0 0 0.1502 0.8491 0.7124 0.9746 0.7291 0 0 0 0 0 0 0.7331 0.3686 0.4528 0.2436 0.2373 0 0 0 0 0 0 0.8894 0.8130 0.2013 0.0054 0.5217 0 0 0 0 0 0 0.6384 0.9649 0.3000 0.2048 0.2233 0 0 0 0 0 0 0.6866 0.9302 0.3413 0.4398 0.0531 0 0 0 0 0 0 0.1080 0.4159 0.2769 0.3304 0 0 0 0 0 0 0 0.0686 0.9871 0.3078

More Answers (1)

David Goodmanson
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

Community Treasure Hunt

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

Start Hunting!

Translated by