Macro nalgebra_macros::stack

source ·
stack!() { /* proc-macro */ }
Expand description

Construct a new matrix by stacking matrices in a block matrix.

Note: Requires the macros feature to be enabled (enabled by default).

This macro facilitates the construction of block matrices by stacking blocks (matrices) using the same MATLAB-like syntax as the matrix! and dmatrix! macros:

// a, b, c and d are matrices
let block_matrix = stack![ a, b;
                           c, d ];

The resulting matrix is stack-allocated if the dimension of each block row and column can be determined at compile-time, otherwise it is heap-allocated. This is the case if, for every row, there is at least one matrix with a fixed number of rows, and, for every column, there is at least one matrix with a fixed number of columns.

stack! also supports special syntax to indicate zero blocks in a matrix:

// a and d are matrices
let block_matrix = stack![ a, 0;
                           0, d ];

Here, the 0 literal indicates a zero matrix of implicitly defined size. In order to infer the size of the zero blocks, there must be at least one matrix in every row and column of the matrix. In other words, no row or column can consist entirely of implicit zero blocks.

§Panics

Panics if dimensions are inconsistent and it cannot be determined at compile-time.

§Examples

use nalgebra::{matrix, SMatrix, stack};

let a = matrix![1, 2;
                3, 4];
let b = matrix![5, 6;
                7, 8];
let c = matrix![9, 10];

let block_matrix = stack![ a, b;
                           c, 0 ];

assert_eq!(block_matrix, matrix![1,  2,  5,  6;
                                 3,  4,  7,  8;
                                 9, 10,  0,  0]);

// Verify that the resulting block matrix is stack-allocated
let _: SMatrix<_, 3, 4> = block_matrix;

The example above shows how stacking stack-allocated matrices results in a stack-allocated block matrix. If all row and column dimensions can not be determined at compile-time, the result is instead a dynamically allocated matrix:

use nalgebra::{dmatrix, DMatrix, Dyn, matrix, OMatrix, SMatrix, stack, U3};

// a and c as before, but b is a dynamic matrix this time
let b = dmatrix![5, 6;
                 7, 8];

// In this case, the number of rows can be statically inferred to be 3 (U3),
// but the number of columns cannot, hence it is dynamic
let block_matrix: OMatrix<_, U3, Dyn> = stack![ a, b;
                                                c, 0 ];

// If necessary, a fully dynamic matrix (DMatrix) can be obtained by reshaping
let dyn_block_matrix: DMatrix<_> = block_matrix.reshape_generic(Dyn(3), Dyn(4));

Note that explicitly annotating the types of block_matrix and dyn_block_matrix is only made for illustrative purposes, and is not generally necessary.