Mirror pattern of the leading diagonal about the middle element of the matrix

Hi All,
I am interested to create the following matrix but unable to think about the logic to create it.
for example : for n = 5 ; the elememts of leading diagonal are 2 1 0 1 2 and rest elements 0
for n = 7, the elements of the leading diagonal are 3 2 1 0 1 2 3 and rest elements are 0.
Any help will be highly appreciated.

 Akzeptierte Antwort

This works for odd ‘n’:
dv = @(n) abs(diag(unique(fix(-n/2:n/2)))); % Create Diagonal Matrix
n = 5;
m5 = dv(n)
n = 7;
m7 = dv(n)
producing:
m5 =
2 0 0 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 1 0
0 0 0 0 2
m7 =
3 0 0 0 0 0 0
0 2 0 0 0 0 0
0 0 1 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 2 0
0 0 0 0 0 0 3
.

6 Kommentare

Thank you so much! This is so perfect! :)
As always, my pleasure!
Thank you!
@Star Strider
One more pattern that comes to my mind, in this format
What should be the code for the leading diagonal elements to be -2 -1 0 1 2 ?
Leave out the abs() call:
dv = @(n) diag(unique(fix(-n/2:n/2))); % Create Diagonal Matrix
n = 5;
m5 = dv(n)
n = 7;
m7 = dv(n)
producing:
m5 =
-2 0 0 0 0
0 -1 0 0 0
0 0 0 0 0
0 0 0 1 0
0 0 0 0 2
m7 =
-3 0 0 0 0 0 0
0 -2 0 0 0 0 0
0 0 -1 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 2 0
0 0 0 0 0 0 3
.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by