RunMat
  • Pricing
RunMat
GitHub
GitHub
Sign inTry in browser
DesktopRuntimePhysicsCADAdministrationAgent

Get RunMat updates

New releases, guides and examples.

Product+
  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download
Math+
  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting
Physics+
  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA
Industries+
  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance
Learn+
  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students
Compare+
  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons
Company+
  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms

Product

  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download

Math

  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting

Physics

  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA

Industries

  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance

Learn

  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students

Compare

  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons

Company

  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms
GitHubXLinkedIn

© Dystr, Inc. · RunMat v0.7.1, Nov 17, 2026

RunMat® is a registered trademark of Dystr, Inc. MATLAB® is a registered trademark of The MathWorks, Inc. RunMat is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.

/
See all docs
Builtin Reference
    • blkdiag
    • cat
    • circshift
    • diag
    • flip
    • fliplr
    • flipud
    • horzcat
    • ipermute
    • kron
    • permute
    • repelem
    • repmat
    • reshape
    • rot90
    • shiftdim
    • squeeze
    • toeplitz
    • tril
    • triu
    • vertcat

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.
NameTypeRequiredDefaultDescription
v or AAnyYes—Input scalar, vector, or matrix.
kNumericScalarYes—Exact signed diagonal offset.
szSizeArgYes—RunMat output size n or [m n].
optionStringScalarYes'vector'RunMat vector extraction option.
classStringScalarYes—RunMat output class override.
likeStringScalarYes'like'RunMat prototype option.
prototypeLikePrototypeYes—Prototype controlling output class and residency.

Returns

D or x
Type
Any
Description
Constructed diagonal matrix or extracted diagonal vector.
NameTypeDescription
D or xAnyConstructed 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
IdentifierWhenMessage
RunMat:diag:InvalidInputInput type, option grammar, size override, or output conversion is invalid.diag: invalid input argument
RunMat:diag:InvalidOffsetDiagonal offset is not a finite integer scalar.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     6

Placing 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     0

Extracting a subdiagonal as a column

A = [1 2 3; 4 5 6; 7 8 9];
d = diag(A, -1)

Expected output:

d =
     4
     8

Building 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     0

Keeping 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     4

Returning a column vector without constructing a matrix

v = [10 20 30];
d = diag(v, 'vector')

Expected output:

d =
    10
    20
    30

Creating a rectangular diagonal matrix

v = [1 2];
R = diag(v, [2 4])

Expected output:

R =
     1     0     0     0
     0     2     0     0

Matching 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

accumarray

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

combinations · nchoosek · perms

Binning

discretize

Indexing

find · ind2sub · sub2ind

Grouping

findgroups · groupcounts · grp2idx · splitapply

Introspection

height · iscolumn · isempty · ismatrix · isrow · isscalar · isvector · length · ndims · numel · size · width

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.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.

Download RunMatOpen Sandbox
On this page
  • Syntax
  • Inputs
  • Returns
  • Errors
  • Construction and extraction
  • RunMat options and residency
  • Examples
  • Creating a diagonal matrix from a vector
  • Placing a vector on an upper diagonal
  • Extracting a subdiagonal as a column
  • Building a logical diagonal
  • Keeping a diagonal result on the GPU
  • Returning a column vector without constructing a matrix
  • Creating a rectangular diagonal matrix
  • Matching a prototype's class and residency
  • Using diag with coding agents
  • FAQ
  • Related Array functions
  • Shape
  • Accumulation
  • Sorting Sets
  • Creation
  • Combinatorics
  • Binning
  • Indexing
  • Grouping
  • Introspection
  • Source you can read
  • About RunMat