Skip to main content
v2026.11,986 entries · CC-BY 4.0

diag Matrix in MATLAB: Create and Extract Diagonals

Use diag in MATLAB to build diagonal matrices from vectors, extract or offset diagonals with k, and zero off-diagonal elements, with size rules and errors.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

In MATLAB, diag does two jobs depending on its input. Given a vector v, D = diag(v) returns a square matrix with the elements of v on the main diagonal and zeros elsewhere. Given a matrix A, x = diag(A) returns the main diagonal as a column vector. A second argument k moves either operation to another diagonal: k = 0 is the main diagonal, k > 0 is above it and k < 0 is below it (MathWorks, diag reference page for R2026b, read 2026-11-12).

What diag is used for in research

Diagonal and near-diagonal matrices turn up wherever a model has independent components: a covariance matrix for uncorrelated variables, a scaling or weighting matrix, the eigenvalue matrix in a decomposition, or a tridiagonal matrix from a finite-difference scheme. diag is how you build those matrices from a vector, and how you pull the diagonal out of a result to inspect it. The same documentation page notes a common one-liner, trace = sum(diag(A)), for the trace of a square matrix. If you are new to the underlying data type, start with matrices in MATLAB; for related matrix operations see transpose in MATLAB, matrix inversion in MATLAB and eigenvalues in MATLAB.

How to install or access it

diag is part of base MATLAB and needs no toolbox; the reference page lists it as introduced before R2006a. Get MATLAB from MathWorks (mathworks.com), where your institution’s licence terms apply, and read the function reference at mathworks.com/help/matlab/ref/diag.html or by typing doc diag in the Command Window. If you do not have a MATLAB licence, GNU Octave and NumPy offer equivalent functions (see the free alternatives table below).

Step-by-step: build and extract diagonals

Create a diagonal matrix from a vector

  1. Define the vector: v = [2 1 -1 -2 -5];
  2. Call D = diag(v). The result is a 5-by-5 matrix with 2, 1, -1, -2, -5 on the main diagonal and zeros elsewhere.
  3. Display it by omitting the semicolon, or inspect it in the Workspace.

Put the vector on a superdiagonal or subdiagonal

  1. Choose the offset: a positive k for a diagonal above the main one, a negative k for one below.
  2. Call D1 = diag(v,1) to place v on the first superdiagonal, or diag(v,-1) for the first subdiagonal.
  3. Check the size. For a vector of N elements the result is square with order N + abs(k), so diag(v,1) on the five-element vector above is 6-by-6.

Extract a diagonal from a matrix

  1. Call x = diag(A) to get the main diagonal as a column vector.
  2. Call x1 = diag(A,-1) to get the first subdiagonal. It has one fewer element than the main diagonal, so for a 6-by-6 matrix A it has 5 elements.

Zero out everything except the main diagonal

  1. Nest the two calls: A1 = diag(diag(A)). The inner call extracts the main diagonal as a vector and the outer call rebuilds a diagonal matrix from it, keeping the main diagonal and setting all other elements to zero.

Build a block-diagonal matrix

  1. Use blkdiag rather than diag when the pieces are matrices instead of scalars: B = blkdiag(A1,A2,A3) aligns the inputs along the diagonal. The inputs can be square or rectangular and of different sizes, and a sparse input gives a sparse output. The reference example combines a 2-by-2, a 3-by-2 and a 2-by-3 matrix into a 7-by-7 result.

Worked example: a tridiagonal matrix from three calls

Because diag(v,k) returns a square matrix whose order is N + abs(k), diagonals of the same order can be added. To build a 4-by-4 tridiagonal matrix with 2 on the main diagonal and 1 on both neighbouring diagonals, each off-diagonal vector needs three elements, since 3 + abs(1) = 4:

T = 2*eye(4) + diag([1 1 1],1) + diag([1 1 1],-1)

The result is the matrix with rows [2 1 0 0], [1 2 1 0], [0 1 2 1] and [0 0 1 2]. This is the same pattern as the MathWorks isdiag example 3*eye(4)+diag([2 2 2],1), which adds a superdiagonal to a scaled identity matrix; that matrix is not diagonal, so isdiag returns 0. Once you have the matrix, diag(T) returns [2;2;2;2] and diag(T,1) returns [1;1;1], which is a quick way to check the construction. The sizes follow directly from the rules above; run the lines in your own session to confirm.

diag, blkdiag and the triangular functions

Use diag when each diagonal entry is a single number. Use blkdiag when each entry on the diagonal is itself a matrix, possibly rectangular, and the result is block diagonal. To keep the lower or upper triangular part of a matrix rather than a single diagonal, the See Also list on the diag page points to tril and triu, with istril and istriu as the matching tests. For sparse matrices with many diagonals, it points to spdiags.

Which function for which task

Task Call Notes
Vector to diagonal matrix diag(v) Square, order = number of elements
Vector to off-diagonal matrix diag(v,k) Order = N + abs(k)
Main diagonal of a matrix diag(A) Column vector
Other diagonal of a matrix diag(A,k) Fewer elements as abs(k) grows
Strip off-diagonal elements diag(diag(A)) Keeps main diagonal only
Place matrices along a diagonal blkdiag(A1,...,AN) Sizes may differ
Test for a diagonal matrix isdiag(A) Logical result
Trace of a square matrix sum(diag(A)) Tip from the diag documentation

Output and how to read it

The key to reading the output is knowing which way the shapes go. A vector in gives a square matrix out; a matrix in gives a vector out. The data table below the article lists worked size cases from the documentation’s own example, including the one-fewer-element rule for extracted off-diagonals.

To confirm that a matrix is diagonal, call tf = isdiag(A). It returns true for a diagonal matrix and false otherwise, and it also returns false for arrays with more than two dimensions. The MathWorks examples show isdiag(eye(4)) returning 1, isdiag(3*eye(4)+diag([2 2 2],1)) returning 0 because of the added superdiagonal, and isdiag(diag(diag(A))) returning 1. The page also states that isdiag(A) is equivalent to isbanded(A,0,0).

Supported input types are single, double, signed and unsigned integers, logical and char, and complex values are supported. An empty input returns an empty result: diag([]) is [].

Troubleshooting

Error with a three-dimensional array

If A has more than two dimensions, diag(A) errors. Take a two-dimensional slice first, for example diag(A(:,:,1)).

Error or empty result with an out-of-range k

For an m-by-n matrix A, the documentation gives the valid range as -(m-1) <= k <= (n-1). A 4-by-4 matrix therefore accepts k from -3 to 3. Check size(A) before choosing an offset.

Result is a vector when you wanted a matrix (or the reverse)

A row or column vector passed to diag always builds a matrix; to extract a diagonal, the input must be a matrix. If you need the diagonal of a matrix and then a matrix again, nest the calls as in diag(diag(A)).

Generating code with MATLAB Coder

For code generation the documentation states that, if you supply k, it must be a real scalar integer. For a variable-size input that is not a vector, use diag(x(:)) or diag(x(:),k) to force vector behaviour, and note that a variable-size 0-by-0 input at run time gives a 0-by-1 result.

Large diagonals and sparse storage

The See Also list on the diag page points to spdiags for sparse diagonal work, and tril, triu, istril and istriu for triangular parts. diag itself supports thread-based environments, GPU arrays and distributed arrays.

Free alternatives

Tool Build from vector Extract What differs from MATLAB
GNU Octave (v11.3.0 manual) M = diag(v), diag(v,k) v = diag(M), diag(M,k) Adds diag(v,m,n), an m-by-n matrix with v on the main diagonal
NumPy (numpy.diag) np.diag(v,k=0) for 1-D v np.diag(x) for 2-D x returns a copy of the k-th diagonal Use numpy.diagonal if you need to write into the extracted diagonal

The NumPy documentation example uses x = np.arange(9).reshape((3,3)): np.diag(x) gives [0 4 8], np.diag(x,k=1) gives [1 5], np.diag(x,k=-1) gives [3 7], and np.diag(np.diag(x)) builds the diagonal matrix with 0, 4, 8. The Octave manual example diag([1,2,3],1) returns a 4-by-4 matrix with 1, 2, 3 on the first superdiagonal. For wider MATLAB workflows see vectorizing MATLAB code.

FAQ

How do I make a diagonal matrix in MATLAB?

Call D = diag(v) with a vector v. The elements of v go on the main diagonal and every other element is zero.

How do I get the diagonal of a matrix in MATLAB?

Call x = diag(A). It returns the main diagonal as a column vector; diag(A,k) returns the k-th diagonal.

How do I put a vector on the superdiagonal?

Use diag(v,1). For an N-element vector the result is (N+1)-by-(N+1), with the vector on the first diagonal above the main one.

How do I set all off-diagonal elements to zero?

Use diag(diag(A)).

How do I compute the trace?

Use sum(diag(A)), the tip given on the MathWorks diag page.

What is the difference between diag and blkdiag?

diag places scalar elements of a vector on one diagonal; blkdiag places whole matrices of any size along the diagonal of a larger matrix.

How do I check that the result is diagonal?

Call isdiag(A), which returns true for a diagonal matrix and false for arrays with more than two dimensions.

Does diag work in GNU Octave and NumPy?

Yes. Both provide a function of the same name with the same offset argument; Octave also accepts diag(v,m,n), and NumPy offers numpy.diagonal for writing into a diagonal.

Sources

Data: MATLAB diag: input form, call and output size, worked cases

Worked output-size cases for the MATLAB diag function (build from a vector, extract from a matrix, offset diagonals, edge cases), compiled from the MathWorks diag reference page and its rules for size and range of k.

Period covered: 2026.

MATLAB diag: input form, call and output size, worked cases
CaseCallInput sizeOutput sizeRule
Vector to main diagonaldiag(v)1-by-5 vector5-by-5Square, order N
Vector to first superdiagonaldiag(v,1)1-by-5 vector6-by-6Order N + abs(k)
Vector to first subdiagonaldiag(v,-1)1-by-5 vector6-by-6Order N + abs(k)
Main diagonal of a matrixdiag(A)6-by-6 matrix6-by-1 column vectorMatrix in, column vector out
First subdiagonal of a matrixdiag(A,-1)6-by-6 matrix5-by-1 column vectorOne fewer element than main diagonal
Empty inputdiag([])0-by-0[] (empty)Returns empty

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about diag Matrix in MATLAB: Create and Extract Diagonals

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →