v0.8.3 tutorial ยท shaped values

Build, slice, and transform Stan containers

Use ordinary Stan literals, arbitrary-rank arrays, arrays of vectors and matrices, indexed mutation, and dimension-aware matrix algorithms while retaining compile-time and binding-time shape diagnostics.

30 checked .stan fixtures

Start with values

Literal delimiters preserve orientation

transformed data {
  array[2,2] real grid = {{1,2},{3,4}};
  vector[3] column = [1,2,3]';
  row_vector[3] row = [4,5,6];
  matrix[2,2] A = [[2,.5],[.5,3]];
}

Braces make arrays. A single bracket row makes a row_vector; transpose makes a vector. Equal-length nested bracket rows make a matrix. Ragged nested literals are rejected before sampling.

One-based selection

Slice and assign without losing base types

data { array[2,3] real x; }
model {
  array[2,3] real work = x;
  work[1,2:3] = rep_array(theta, 2);
  work[:,1] += theta;
  target += sum(work);
}

Scalar, partial, range, all-index, and chained indexing use Stan's one-based convention. Arrays may contain vectors or matrices: array[2] vector[3] and array[4] matrix[2,2] retain their element orientation after slicing.

Linear algebra

Compose a checked matrix pipeline

matrix[3,2] X = [[1,0],[1,1],[1,2]];
matrix[2,2] gram = crossprod(X);
matrix[2,2] L = cholesky_decompose(gram);
matrix[3,2] Q = qr_thin_Q(X);
vector[3] fitted = X * beta;
y ~ multi_normal(fitted, Sigma);

The runtime distinguishes vector, row_vector, and matrix. Products follow orientation; .* and ./ remain explicit elementwise operations. Also available are inverse/determinant/log determinant, SPD solves, blocks/rows/columns, diagonal pre/post multiplication, quadratic forms, cross products, and covariance or Cholesky multivariate-normal kernels.

Fail early

Shape mismatches name both operands

Compilation and data binding check dimensions, array rank, base type, matrix inner dimensions, square/SPD requirements, slice bounds, and assignment shape. Scalar broadcasting is allowed; vector-versus-row-vector elementwise arithmetic and differently shaped non-scalars are rejected. The exact compatibility matrix is in the source contract.

Run verified source

Continue with examples 13โ€“37

Browse all forty-one ordinary .stan fixtures. Examples 13, 17โ€“28 cover real containers and matrix pipelines; 31โ€“37 add complex conjugate algebra, nested tuples, CSR kernels, reductions, and SPD operations.

./gradlew validateModelScripts