#矩阵运算
一个实现了运算符和索引 trait 的小型矩阵类型,因此可以写 a * b、a .* b 和 m[i, j]。
#代码
nabi
// A dense row-major matrix of f64.
struct Matrix {
rows: usize;
cols: usize;
data: List<f64>;
}
impl Matrix {
fn zeros(rows: usize, cols: usize) -> Matrix {
Matrix { rows: rows, cols: cols, data: List::filled(rows * cols, 0.0) }
}
fn from_rows(rows: List<List<f64>>) -> Matrix {
let m = Matrix::zeros(rows.len(), rows[0].len());
for i in 0..m.rows {
for j in 0..m.cols { m[i, j] = rows[i][j]; }
}
m
}
fn identity(n: usize) -> Matrix {
let m = Matrix::zeros(n, n);
for i in 0..n { m[i, i] = 1.0; }
m
}
fn transpose(self) -> Matrix {
let t = Matrix::zeros(self.cols, self.rows);
for i in 0..self.rows {
for j in 0..self.cols { t[j, i] = self[i, j]; }
}
t
}
}
// m[i, j] reads an element ...
impl index::Index<(usize, usize)> for Matrix {
type Output = f64;
fn index(self, (i, j): (usize, usize)) -> f64 {
self.data[i * self.cols + j]
}
}
// ... and m[i, j] = v writes one.
impl index::IndexSet<(usize, usize), f64> for Matrix {
fn index_set(ref self, (i, j): (usize, usize), value: f64) {
self.data[i * self.cols + j] = value;
}
}
impl ops::Add for Matrix {
type Output = Matrix;
fn add(self, rhs: Matrix) -> Matrix {
Matrix { rows: self.rows, cols: self.cols, data: self.data .+ rhs.data }
}
}
impl ops::Mul for Matrix {
type Output = Matrix;
fn mul(self, rhs: Matrix) -> Matrix {
let out = Matrix::zeros(self.rows, rhs.cols);
for i in 0..self.rows {
for j in 0..rhs.cols {
let sum = 0.0;
for k in 0..self.cols { sum += self[i, k] * rhs[k, j]; }
out[i, j] = sum;
}
}
out
}
}
// Scalar scaling: Matrix * f64.
impl ops::Mul<f64> for Matrix {
type Output = Matrix;
fn mul(self, k: f64) -> Matrix {
Matrix { rows: self.rows, cols: self.cols, data: self.data .* k }
}
}
// Element-wise (Hadamard) product: a .* b.
impl ops::DotMul for Matrix {
type Output = Matrix;
fn dot_mul(self, rhs: Matrix) -> Matrix {
Matrix { rows: self.rows, cols: self.cols, data: self.data .* rhs.data }
}
}
impl Display for Matrix {
fn fmt(self, ref f: Formatter) throws (FmtError) {
for i in 0..self.rows {
try f.write_str("[");
for j in 0..self.cols {
try f.write_str(f"{self[i, j]:6.1}");
}
try f.write_str(" ]\n");
}
}
}
let a = Matrix::from_rows([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]);
let b = Matrix::from_rows([[7.0, 8.0], [9.0, 10.0], [11.0, 12.0]]);
println(f"A =\n{a}");
println(f"A^T =\n{a.transpose()}");
println(f"A * B =\n{a * b}");
println(f"A + A =\n{a + a}");
println(f"A .* A =\n{a .* a}");
println(f"A * 0.5 =\n{a * 0.5}");
let i3 = Matrix::identity(3);
let same = a * i3;
println(f"A * I == A: {same.data == a.data}");
A =
[ 1.0 2.0 3.0 ]
[ 4.0 5.0 6.0 ]
A^T =
[ 1.0 4.0 ]
[ 2.0 5.0 ]
[ 3.0 6.0 ]
A * B =
[ 58.0 64.0 ]
[ 139.0 154.0 ]
A + A =
[ 2.0 4.0 6.0 ]
[ 8.0 10.0 12.0 ]
A .* A =
[ 1.0 4.0 9.0 ]
[ 16.0 25.0 36.0 ]
A * 0.5 =
[ 0.5 1.0 1.5 ]
[ 2.0 2.5 3.0 ]
A * I == A: true
#讲解
- Nabi 中的每个运算符都是 trait 方法调用。有了
impl ops::Add for Matrix,a + a就脱糖为ops::Add::add(a, a)(3.1 运算符分派,Add,Mul)。 - 同一个运算符可以针对不同的右侧类型实现多次。
impl ops::Mul for Matrix是矩阵乘法,impl ops::Mul<f64> for Matrix是标量乘法;编译器根据操作数的类型选择 impl。 .*这样带点前缀的运算符脱糖为另一组用于逐元素运算的 trait(DotMul),所以矩阵乘法*和 Hadamard 积.*可以并存。在内部,self.data .+ rhs.data和self.data .* k是作用于List<f64>本身的同样的运算符,各自是一个循环,没有中间列表(3.3 广播运算符)。- 逗号分隔的索引会组成一个元组,所以读取
m[i, j]经过Index<(usize, usize)>,写入m[i, j] = v经过IndexSet<(usize, usize), f64>,其第二个参数是写入值的类型。写入方法接受ref self,以便就地修改矩阵(3.6 索引与切片)。 - 有了
impl Display for Matrix,f-string 中的{a}会输出整个矩阵。每个元素用{x:6.1}指定宽度和精度(结构体、枚举与 trait)。 - 这个示例展示了自定义类型如何接入运算符。对于数值计算,core 库已经提供了
Array<T, N>,这是一个支持切片、广播和融合点表达式的 n 维数组(数组与数值计算)。
发现错误? 在 GitHub 上编辑此页 最后更新: