triu

Upper triangular part of a matrix.

Category: Mathematics > Linear Algebra

Syntax

U = triu(A)

Keeps the main diagonal and everything above it; the rest becomes zero.

U = triu(A, k)

Keeps the elements on and above the k-th diagonal.

Description

triu(A) zeroes the elements below the main diagonal. With k = 1 the diagonal is removed too, leaving the strictly upper part.

The matrix need not be square. For a wide or tall matrix the diagonal is still the set of positions (i, i + k).

Input arguments

A
Matrix (any class).
k
Integer diagonal offset: 0 is the main diagonal, positive values are above it, negative values below. Default 0.

Output arguments

U
Matrix of the same size and class as A.

Example

Upper part with offsets

A = magic(3);
triu(A)
triu(A, 1)
Output
ans = 3×3

     8     1     6
     0     5     7
     0     0     2
ans = 3×3

     0     1     6
     0     0     7
     0     0     0

See also

tril diag istriu lu