triu — Extract the upper-triangular part of each matrix page.
triu(A) preserves the main diagonal and entries above it. triu(A,k) shifts the retained diagonal by the finite integer offset k.
Syntax
B = triu(A)
B = triu(A, k)Inputs
A- Type
Any- Required
- Yes
- Description
- Dense numeric, logical, character, complex, or resident array.
k- Type
NumericScalar- Required
- Yes
- Description
- Finite integer-valued diagonal offset.
Returns
B- Type
Any- Description
- Upper-triangular output with the input class and shape.
Errors
RunMat:triu:TooManyInputs- When
- More than one optional argument is supplied after A.
- Message
triu: too many input arguments
RunMat:triu:TooManyOutputs- When
- More than one output is requested.
- Message
triu: too many output arguments
RunMat:triu:InvalidOffset- When
- The diagonal offset is not a finite integer-valued real scalar in the platform index range.
- Message
triu: invalid diagonal offset
Behavior
The output has the same full shape as A. In RunMat extension mode, arrays with more than two dimensions are masked independently page by page; strict compatibility mode rejects paged input.
Positive k removes lower diagonals and the diagonals below the shifted boundary; negative k retains subdiagonals.
Dense single, double, logical arrays, character, complex floating, and all eight native integer classes are supported. Array class and precision are preserved; a scalar logical is normalized to the runtime's double scalar representation, and masked character entries become the NUL character.
Native complex-integer components are structurally masked with a same-class zero. Strings, cells, sparse arrays, structures, objects, symbolic values, and callable/execution carriers are rejected.
k may be a real floating, logical, or native integer scalar. Native integers are decoded exactly; nonfinite, fractional, nonscalar, complex, and out-of-platform-range offsets are rejected.
Zero requested outputs still validates arguments and compatibility. More than one requested output is rejected before masking or provider access.
GPU and execution
Resident floating input first uses the owning provider's triu operation. If that hook is unavailable, RunMat gathers once, masks on the host, and restores through that same provider.
Resident integer input uses exact gather/mask/restoration because the floating provider hook is not an integer authority. If no owner provider is available, automatic residency may produce a host result.
The optional offset is validated after an admitted gather when resident. Triangular masking is a fusion boundary and does not replay an operational provider failure as a second numerical operation.
Examples
Main and upper diagonals
A = [1 2 3; 4 5 6; 7 8 9];
U = triu(A)Expected output:
U = [1 2 3; 0 5 6; 0 0 9]Include one subdiagonal
A = reshape(1:9,3,3);
U = triu(A,-1);Keep one subdiagonal
A = magic(4);
U = triu(A,-1);Drop the main diagonal
A = [1 2 3;4 5 6;7 8 9];
strict = triu(A,1);Mask every matrix page
T = reshape(1:18,[3 3 2]);
U = triu(T);Preserve wide integer values
wide = 0x0020000000000001u64; largest = 0xFFFFFFFFFFFFFFFFu64; A = uint64([wide 4; 5 largest]); U = triu(A);Keep a resident single matrix resident
G = gpuArray(single([1 2;3 4])); U = triu(G);Preserve residency with an offset
G = gpuArray(single(reshape(1:25,5,5)));
U = triu(G,-2);Using triu with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how triu changes the result.
Run a small triu example, explain the result, then change one input and compare the output.
FAQ
What happens when k is a large negative offset?⌄
The entire matrix is preserved; triu never removes elements above the chosen diagonal.
Does triu work with logical arrays?⌄
Yes. Elements below the retained diagonal become false, while the rest keep their logical values.
How are complex numbers handled?⌄
Each retained element keeps its real and imaginary parts. Masked elements become zero in both components.
What about empty matrices or zero-sized dimensions?⌄
triu returns an array of the same shape. Trailing zero-sized dimensions remain empty pages.
Does triu change the class of character arrays?⌄
No. Character arrays remain character arrays; masked entries become NUL characters.
Can triu operate on N-D arrays?⌄
Yes when the triu-paged-input RunMat extension is enabled. Each trailing page is masked independently and all dimensions are retained.
Does triu convert integer data to double?⌄
No. Native integer data and typed zeros retain the exact input class, including values not exactly representable as binary64.
Related Array functions
Shape
blkdiag · cat · circshift · diag · flip · fliplr · flipud · horzcat · ipermute · kron · permute · repelem · repmat · reshape · rot90 · shiftdim · squeeze · toeplitz · tril · 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
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.