Qu

diag

Builtin index · Core maths

result = diag(M) or diag(v)

Input: M · Output: result

What it is

Overloaded on argument type: diag(M), where M is an r×c Mat, returns its main diagonal as a length-min(r,c) Vec; diag(v), where v is a length-n Vec (or scalar/other coercible value), returns an n×n Mat with v's entries on the diagonal and zeros elsewhere.

Overloads

M can be Mat, Vec, scalar, or matrix.

2 forms. Each carries its own inputs, outputs and worked example — pick the tab for the one you are calling.

CodeInputOutputDescription
result = diag(M) or diag(v)
M Mat or Vecnot documented yet
result Vec or Mat
—

Examples

Written for this form and run by the build -- the output below is what the engine actually produced.

M = [1, 2; 3, 4]
print(diag(M))   # [1, 4]

output
[1, 4]
CodeInputOutputDescription
result = diag(M) or diag(v)
M Vec, scalar, Mat, or matrixnot documented yet
result Vec or Mat
v a length-n Vec (or scalar/other coercible value). Builds a new n×n Mat with v's entries on the diagonal and zeros elsewhere — construction, the opposite direction from the matrix case.

Examples

Written for this form and run by the build -- the output below is what the engine actually produced.

print(diag([1, 2, 3]))   # [1, 0, 0; 0, 2, 0; 0, 0, 3]

output
[1, 0, 0; 0, 2, 0; 0, 0, 3]

How it works

diag(v) builds a diagonal matrix from a vector; diag(A) extracts the diagonal of a matrix. Both spellings, because both are what the name means and which one applies is unambiguous from the argument -- the same convention numpy and MATLAB use.

From the note above this builtin in the interpreter, where the reasoning was written down as it was built.