Libmir Archive

Linear Algebra in D — Matrix Operations with mir-blas

Matrix-vector and matrix-matrix products, dot products, and BLAS operations on ndslice in D with mir-blas. Compiled against current Mir source.

How to do linear algebra in D with mir-blas — BLAS operations that take ndslice directly, no manual pointers or leading dimensions. For decompositions (LU, Cholesky, SVD, eigenvalues) see mir-lapack; for a higher-level API see lubeck.

Examples compile against current mir-blas + cblas. BLAS routines need a backing implementation (OpenBLAS, MKL, …) at link time. mir-blas accepts ndslice and handles the storage translation, so you write gemm(alpha, A, B, beta, C) instead of juggling raw pointers and lda arguments.

Matrix–vector product (gemv)

import mir.blas;
import mir.ndslice;

auto A = [1.0, 2, 3, 4, 5, 6].sliced(2, 3).canonical;  // 2×3
auto x = [1.0, 1, 1].sliced.canonical;                 // length 3
auto y = slice!double(2).canonical;                    // output length 2
gemv(1.0, A, x, 0.0, y);                                // y = 1·A·x + 0·y

gemv computes y = alpha·A·x + beta·y. The .canonical kind gives BLAS the strided layout it expects.

Matrix–matrix product (gemm)

import mir.blas;
import mir.ndslice;

auto A = [1.0, 2, 3, 4, 5, 6].sliced(2, 3).canonical;  // 2×3
auto B = [1.0, 0, 0, 1, 1, 1].sliced(3, 2).canonical;  // 3×2
auto C = slice!double(2, 2).canonical;                 // 2×2 output
gemm(1.0, A, B, 0.0, C);                                // C = A·B

gemm is the workhorse: C = alpha·A·B + beta·C. Shapes must be conformable (here 2×3 · 3×2 → 2×2).

Dot product

import mir.blas;
import mir.ndslice;

auto x = [1.0, 1, 1].sliced.canonical;
auto d = dot(x, [2.0, 2, 2].sliced.canonical);   // 1·2 + 1·2 + 1·2 = 6

Where to go next

On this page