# MATLAB 对角矩阵

## 在 MATLAB 中使用 `diag()` 函数制作对角矩阵

``````clc
vector = [1 2 3 4 5];
diagonal = diag(vector)
``````

``````diagonal =

1     0     0     0     0
0     2     0     0     0
0     0     3     0     0
0     0     0     4     0
0     0     0     0     5
``````

``````clc
vector = [1 2 3 4 5];
diagonal = diag(vector,1)
``````

``````diagonal =

0     1     0     0     0     0
0     0     2     0     0     0
0     0     0     3     0     0
0     0     0     0     4     0
0     0     0     0     0     5
0     0     0     0     0     0
``````

``````clc
vector = [1 2 3;4 5 6;7 8 9]
diagonal = diag(vector)
``````

``````vector =

1     2     3
4     5     6
7     8     9

diagonal =

1
5
9
``````

## 在 MATLAB 中使用 `spdiags()` 函数制作对角矩阵

``````clc
v1 = [1 2 3 4 5].';
v2 = [2 2 2 2 2].';
v3 = [3 3 3 3 3].';
diagonal = spdiags([v2 v1 v3],-1:1,5,5);
matrix = full(diagonal)
``````

``````matrix =

1     3     0     0     0
2     2     3     0     0
0     2     3     3     0
0     0     2     4     3
0     0     0     2     5
``````

``````clc
v1 = [1 2 3 4 5].';
v2 = [2 2 2 2 2].';
v3 = [3 3 3 3 3].';
diagonal = spdiags([v2 v1 v3],-1:1,5,5);
matrix1 = full(diagonal)

v4 = [9 9 9 9 9].';
diagonal = spdiags(v4,0,diagonal);
matrix2 = full(diagonal)
``````

``````matrix1 =

1     3     0     0     0
2     2     3     0     0
0     2     3     3     0
0     0     2     4     3
0     0     0     2     5

matrix2 =

9     3     0     0     0
2     9     3     0     0
0     2     9     3     0
0     0     2     9     3
0     0     0     2     9
``````

``````clc
v1 = [1 2 3 4 5].';
v2 = [2 2 2 2 2].';
v3 = [3 3 3 3 3].';
diagonal = spdiags([v2 v1 v3],-1:1,5,5);
matrix = full(diagonal)

diag_Values = spdiags(matrix)
``````

``````matrix =

1     3     0     0     0
2     2     3     0     0
0     2     3     3     0
0     0     2     4     3
0     0     0     2     5

diag_Values =

2     1     0
2     2     3
2     3     3
2     4     3
0     5     3
``````

• MATLAB 矩阵转置