packages

linalg::ops

On this page

Operators for matrix code (feature ops, on by default):

a @ b, a ⊡ b matrix product (level of *) a ⊗ b Kronecker product; outer product of two vectors (*) a \ b, a ⧵ b solve a x = b, MATLAB's left division (/) a† adjoint, the conjugate transpose (postfix, level of ?)

Every operator also has a named form (linalg::matmul(a, b), ...).

Traits

MatMulSource

pub trait MatMul<Rhs>

a @ b (or a ⊡ b): the matrix product, with a vector on either side as a column (right) or a row (left), and the dot product of two vectors. Binds like *, so a @ b .+ c is (a @ b) .+ c. Shapes that do not fit panic, naming both, as the broadcast operators do; linalg::matmul throws instead.

nabi
use core::array::{Array, Matrix, Vector};

let a: Matrix<f64> = [[1, 2], [3, 4]];
let x: Vector<f64> = [1, 1];
assert(a @ x == Vector::<f64>::from([3.0, 7.0]));
assert((a @ a)[1, 1] == 22.0);
assert(a ⊡ a == a @ a);
assert(x @ x == 2.0);

KronSource

pub trait Kron<Rhs>

a ⊗ b: the Kronecker product of two matrices, the outer product (a matrix) of two vectors. Binds like *.

nabi
use core::array::{Array, Matrix, Vector};

let i: Matrix<f64> = linalg::eye(2);
let b: Matrix<f64> = [[1, 2], [3, 4]];
assert((i ⊗ b).shape() == [4, 4]);
let u: Vector<f64> = [1, 2];
assert((u ⊗ u)[1, 1] == 4.0);

SolveSource

pub trait Solve<Rhs>

a \ b (or a ⧵ b): x with a x = b, MATLAB's left division, by LU for a square a and least squares (lstsq) otherwise. Operators do not throw, so the answer is a Result: try (a \ b).get(). Binds like /.

nabi
use core::array::{Array, Matrix, Vector};

let a: Matrix<f64> = [[3, 1], [1, 2]];
let b: Vector<f64> = [9, 8];
let x = try (a \ b).get();
assert(x == Vector::<f64>::from([2.0, 3.0]));
assert(try (a ⧵ b).get() == x);
let s: Matrix<f64> = [[1, 2], [2, 4]];
assert((s \ b).is_err());

AdjointSource

pub trait Adjoint

a†: the adjoint (conjugate transpose); for a real matrix the transpose, as a view. Postfix, binding like ?: a† @ a is (a†) @ a.

nabi
use core::array::Matrix;
use core::num::Complex;

let a: Matrix<f64> = [[1, 2, 3]];
assert(a†.shape() == [3, 1]);
let z: Matrix<Complex<f64>> = [[1.0 + 1.0i]];
assert(z†[0, 0] == Complex::new(1.0, -1.0));