diag — Create diagonal matrices or extract diagonals in MATLAB and RunMat.
diag constructs a diagonal matrix from a vector or extracts one diagonal from a matrix. The four public forms follow MATLAB semantics; size, vector, class, and like forms are separately gated RunMat extensions.
Syntax
D = diag(v)
D = diag(v, k)
x = diag(A)
x = diag(A, k)
D = diag(v, sz)
D = diag(v, k, sz)All supported diag forms
D = diag(v)
D = diag(v, k)
x = diag(A)
x = diag(A, k)
D = diag(v, sz)
D = diag(v, k, sz)
x = diag(A, 'vector')
D = diag(v, class)
D = diag(v, 'like', prototype)Inputs
v or A- Type
Any- Required
- Yes
- Description
- Input scalar, vector, or matrix.
k- Type
NumericScalar- Required
- Yes
- Description
- Exact signed diagonal offset.
sz- Type
SizeArg- Required
- Yes
- Description
- RunMat output size n or [m n].
option- Type
StringScalar- Required
- Yes
- Default
'vector'- Description
- RunMat vector extraction option.
class- Type
StringScalar- Required
- Yes
- Description
- RunMat output class override.
like- Type
StringScalar- Required
- Yes
- Default
'like'- Description
- RunMat prototype option.
prototype- Type
LikePrototype- Required
- Yes
- Description
- Prototype controlling output class and residency.
Returns
D or x- Type
Any- Description
- Constructed diagonal matrix or extracted diagonal vector.
Errors
RunMat:diag:InvalidInput- When
- Input type, option grammar, size override, or output conversion is invalid.
- Message
diag: invalid input argument
RunMat:diag:InvalidOffset- When
- Diagonal offset is not a finite integer scalar.
- Message
diag: invalid diagonal offset
Construction and extraction
diag(v) constructs a square matrix with vector v on its main diagonal. diag(v,k) places it above (k>0) or below (k<0) the main diagonal and grows each output extent by abs(k).
diag(A) and diag(A,k) extract a column vector from the specified matrix diagonal. A nonexistent diagonal returns an empty 0×1 column vector.
Empty vector construction returns 0×0 without an offset, or an abs(k) square zero matrix with one. The offset must be a finite exact signed integer scalar.
Logical data remains logical, complex data retains both components, and character data uses space padding away from constructed diagonals. Native single and all eight integer classes are preserved where supported.
Strict MATLAB mode rejects nontrivial N-D input; RunMat mode separately gates trailing singleton dimensions.
RunMat options and residency
RunMat mode provides diag(v,'vector'), explicit rectangular sizes such as [m n], output-class overrides, and diag(v,'like',prototype). Each extension has its own compatibility gate.
The like prototype controls output class and residency. Supported resident real and logical inputs use owner-validated provider diagonal hooks; unsupported direct classes follow a checked gather, host operation, and owner-preserving restore path.
The provider route is a structural fusion boundary. It does not imply an elementwise diagonal kernel.
Automatic offload may keep results resident without an explicit gpuArray call. An explicit gpuArray input or like prototype still selects its registered owner and device, and validated fallback must preserve that intent.
Examples
Creating a diagonal matrix from a vector
v = [4 5 6];
D = diag(v)Expected output:
D =
4 0 0
0 5 0
0 0 6Placing a vector on an upper diagonal
v = [1 2 3];
U = diag(v, 1)Expected output:
U =
0 1 0 0
0 0 2 0
0 0 0 3
0 0 0 0Extracting a subdiagonal as a column
A = [1 2 3; 4 5 6; 7 8 9];
d = diag(A, -1)Expected output:
d =
4
8Building a logical diagonal
mask = logical([1 0 1 0]);
M = diag(mask)Expected output:
M =
1 0 0 0
0 0 0 0
0 0 1 0
0 0 0 0Keeping a diagonal result on the GPU
G = gpuArray([2; 4; 8]);
D = diag(G);
firstTwo = gather(D(1:2, 1:2))Expected output:
firstTwo =
2 0
0 4Returning a column vector without constructing a matrix
v = [10 20 30];
d = diag(v, 'vector')Expected output:
d =
10
20
30Creating a rectangular diagonal matrix
v = [1 2];
R = diag(v, [2 4])Expected output:
R =
1 0 0 0
0 2 0 0Matching a prototype's class and residency
G = gpuArray([1 3 5]');
D = diag([1 2 3], 'like', G)Using diag with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how diag changes the result.
Run a small diag example, explain the result, then change one input and compare the output.
FAQ
Does diag always return a square matrix?⌄
The vector form does. RunMat mode separately gates vector extraction and explicit rectangular-size options.
What if the requested diagonal is outside matrix bounds?⌄
The result is an empty 0×1 column vector.
Can I use logical or character arrays?⌄
Yes. Logical results stay logical; constructed character matrices use spaces away from the diagonal.
Does diag support complex values?⌄
Yes. Diagonal placement or extraction retains the real and imaginary components.
How do offsets work with vectors?⌄
The output square grows by abs(k); positive offsets move up and negative offsets move down.
Can I make a non-square matrix?⌄
RunMat mode supports the gated explicit-size option, including diag(v,[m n]) and diag(v,k,[m n]).
What if the vector is empty?⌄
Without an offset the result is 0×0; with an offset it is an abs(k) square zero matrix.
Do GPU results remain resident?⌄
Supported owner-validated provider hooks stay resident. Other supported classes use checked gather and owner-preserving restore when possible.
Must the offset be an integer?⌄
Yes. Non-integer, non-finite, or out-of-range offsets raise an error.
Does diag mutate its input?⌄
No; it constructs a separate result.
How can output match another array?⌄
RunMat mode provides the separately gated like prototype option for class and residency.
Is single precision supported?⌄
Yes. Native single data remains single; a single-precision like prototype can also request it.
Related Array functions
Shape
blkdiag · cat · circshift · flip · fliplr · flipud · horzcat · ipermute · kron · permute · repelem · repmat · reshape · rot90 · shiftdim · squeeze · toeplitz · tril · triu · vertcat
Accumulation
Sorting Sets
argsort · intersect · ismember · ismembertol · issorted · issortedrows · setdiff · setxor · sort · sortrows · union · unique
Creation
colon · createArray · empty · eye · false · full · inf · int16.empty · int32.empty · int64.empty · int8.empty · linspace · logspace · magic · meshgrid · nan · ndgrid · nonzeros · ones · peaks · rand · randi · randn · randperm · range · sparse · spdiags · speye · spones · sprand · true · uint16.empty · uint32.empty · uint64.empty · uint8.empty · zeros
Combinatorics
Binning
Grouping
Source you can read
Every RunMat function's source is public. Read exactly how diag is executed, line by line, in Rust.
- View the source for diag in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.