blkdiag — Construct block diagonal matrices from scalar, vector, matrix, sparse, complex, logical, character, or gpuArray blocks.
B = blkdiag(A1, A2, ...) places each input block down the diagonal of a new matrix. Rows and columns are accumulated from the input blocks, and all off-block entries are filled with zeros or spaces for character arrays.
Syntax
B = blkdiag()
B = blkdiag(A1, An...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
A1 | Any | Yes | — | First scalar, vector, matrix, sparse matrix, or gpuArray block. |
An | Any | Variadic | — | Additional blocks placed down and right from the previous block. |
Returns
| Name | Type | Description |
|---|---|---|
B | Any | Block diagonal matrix containing each input along the diagonal. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:blkdiag:InvalidInput | An input class, dimensionality, or block conversion is unsupported. | blkdiag: invalid input |
RunMat:blkdiag:SizeOverflow | The block diagonal output dimensions or allocation size exceed addressable memory. | blkdiag: output size exceeds maximum supported size |
RunMat:blkdiag:GpuError | A required gpuArray gather or upload operation fails. | blkdiag: gpuArray operation failed |
How blkdiag works
blkdiag()returns the canonical empty0 x 0double matrix.- Numeric scalars are treated as
1 x 1blocks, vectors and matrices keep their two-dimensional shape, and inputs with only singleton trailing dimensions are accepted. - All-logical inputs return a logical array. Mixed logical and numeric inputs return a numeric array.
- If any input is sparse and no input is character, the output is sparse when complex inputs are real-valued; dense numeric, logical, and real-valued complex blocks contribute only their nonzero entries.
- If any input is complex and no input is character, the output is complex and real, logical, and sparse inputs are promoted into the real part when needed.
- Sparse inputs mixed with non-real complex blocks currently return a dense complex result because RunMat does not yet have a complex sparse matrix representation.
- Single-precision dense blocks preserve single dtype when all dense numeric blocks share that dtype.
- Character blocks are supported when every input is a character array; off-block entries are spaces.
- String arrays, cell arrays, and non-matrix higher-dimensional inputs raise errors.
- gpuArray inputs can be mixed with host numeric, logical, or complex blocks. Dense numeric, logical, and complex results remain gpu-resident; sparse results remain host sparse matrices.
Does RunMat run blkdiag on the GPU?
blkdiag is GPU-aware but not fused. It materialises a fresh block diagonal array and therefore acts as a fusion sink.
GPU memory and residency
gpuArray inputs are gathered to host for block placement, then dense numeric, logical, and complex results are uploaded back to the active provider. Sparse results remain host sparse matrices.
Examples
Combining dense matrix blocks
A = [1 2; 3 4];
B = [5 6];
C = blkdiag(A, B)Expected output:
C =
1 2 0 0
3 4 0 0
0 0 5 6Using scalar and vector blocks
D = blkdiag(1, [2 3 4], 5)Expected output:
D =
1 0 0 0 0
0 2 3 4 0
0 0 0 0 5Preserving sparse output
S = sparse([1 2], [1 2], [10 20], 2, 2);
T = blkdiag(S, [0; 30])Expected output:
T = sparse([1 2 4], [1 2 3], [10 20 30], 4, 3)Building a complex block diagonal matrix
Z = blkdiag(1 + 2i, [3; 4])Keeping all-gpuArray inputs on the GPU
G1 = gpuArray([1; 2]);
G2 = gpuArray([3 4]);
G = blkdiag(G1, G2);
result = gather(G)Expected output:
result =
1 0 0
2 0 0
0 3 4Using blkdiag with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how blkdiag changes the result.
Run a small blkdiag example, explain the result, then change one input and compare the output.
FAQ
What class does blkdiag return?⌄
All-logical inputs return logical. Sparse inputs return sparse unless character input is present or a non-real complex block requires complex output. Complex inputs promote the output to complex when needed. Otherwise numeric dense output is returned.
Does blkdiag preserve sparse matrices?⌄
Yes for real-valued sparse outputs. If any input is sparse and the output is not character or non-real complex, RunMat builds a sparse CSC result and keeps only nonzero entries from dense numeric, logical, and real-valued complex blocks. Non-real complex entries currently promote the result to dense complex because RunMat does not yet provide complex sparse storage.
Can I mix host arrays and gpuArray values?⌄
Yes, for dense numeric, logical, and complex blocks. RunMat gathers gpuArray inputs, assembles the result, and uploads dense results back to the provider. Sparse results remain host sparse matrices.
Are character arrays supported?⌄
Yes, when every input is a character array. The original character blocks are placed on the diagonal and spaces fill off-block positions.
Does blkdiag accept 3-D arrays?⌄
Only inputs whose trailing dimensions are singleton are accepted. Non-matrix higher-dimensional inputs raise an error.
Related Array functions
Shape
cat · circshift · diag · flip · fliplr · flipud · horzcat · ipermute · kron · permute · repelem · repmat · reshape · rot90 · squeeze · toeplitz · tril · triu · vertcat
Grouping
accumarray · combinations · discretize · findgroups · groupcounts · grp2idx · splitapply
Sorting Sets
argsort · intersect · ismember · ismembertol · issorted · issortedrows · setdiff · setxor · sort · sortrows · union · unique
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how blkdiag is executed, line by line, in Rust.
- View the source for blkdiag in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 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.