D = diag(v,k) places
the elements of vector v on the kth
diagonal. k=0 represents the main diagonal, k>0 is
above the main diagonal, and k<0 is below the
main diagonal.

C/C++ Code Generation Generate C and C++ code using MATLAB® Coder™.

Usage notes and limitations:

If you supply k, then it must be
a real and scalar integer value.

For variable-size inputs that are variable-length
vectors (1-by-: or :-by-1), diag:

Treats the input as a vector

Returns a matrix with the input vector along the specified diagonal

For variable-size inputs that are not variable-length
vectors, diag:

Treats the input as a matrix

Does not support inputs that are vectors at run time

Returns a variable-length vector

If the input is variable-size (:m-by-:n) and has shape 0-by-0 at run time, then the output is
0-by-1, not 0-by-0. However, if the input is a constant size 0-by-0, then the output is
[].

For variable-size inputs that are not variable-length
vectors (1-by-: or :-by-1), diag treats the input
as a matrix from which to extract a diagonal vector. This behavior
occurs even if the input array is a vector at run time. To force diag to
build a matrix from variable-size inputs that are not 1-by-: or :-by-1,
use:

GPU Code Generation Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.

Usage notes and limitations:

If you supply k, then it must be a real and scalar integer
value.

For variable-size inputs that are variable-length vectors (1-by-: or :-by-1),
diag:

Treats the input as a vector

Returns a matrix with the input vector along the specified diagonal

For variable-size inputs that are not variable-length vectors, diag:

Treats the input as a matrix

Does not support inputs that are vectors at run time

Returns a variable-length vector

If the input is variable-size (:m-by-:n) and has shape 0-by-0 at run time, then the
output is 0-by-1, not 0-by-0. However, if the input is a constant size 0-by-0, then the output
is [].

For variable-size inputs that are not variable-length vectors (1-by-: or :-by-1),
diag treats the input as a matrix from which to extract a diagonal
vector. This behavior occurs even if the input array is a vector at run time. To force
diag to build a matrix from variable-size inputs that are not 1-by-: or
:-by-1, use:

diag(x(:)) instead of diag(x)

diag(x(:),k) instead of diag(x,k)

Thread-Based Environment Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.