MATLAB diag Function Explained
The diag function is used to create a diagonal matrix. Here is the specific usage:
- Create a diagonal matrix: The diag function takes a vector as input and returns a diagonal matrix with that vector as its diagonal elements.
A = [1 2 3];
B = diag(A);
% 结果是:
% B =
% 1 0 0
% 0 2 0
% 0 0 3
- Extract diagonal elements: The diag function can be used to extract the diagonal elements of a matrix.
C = [1 0 0; 0 2 0; 0 0 3];
D = diag(C);
% 结果是:
% D =
% 1
% 2
% 3
- Extract the k-th diagonal of a matrix: The elements of the k-th diagonal of a matrix can be extracted using the second parameter of the diag function.
E = [1 2 3; 4 5 6; 7 8 9];
F = diag(E, 1);
% 结果是:
% F =
% 2
% 6
With these methods, the diag function can be used flexibly to operate on the elements of a diagonal matrix.