Skip to content

Instantly share code, notes, and snippets.

@mmatyas
Created May 17, 2016 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmatyas/639fc151dda34bb6dd07ee28120677a5 to your computer and use it in GitHub Desktop.
Save mmatyas/639fc151dda34bb6dd07ee28120677a5 to your computer and use it in GitHub Desktop.
Rust matrix multiplication example
// Based on
// https://gist.githubusercontent.com/csherratt/7634597/raw/b05699f444ab552eb79a7f7c0e1c5ac235c5222c/mat4.rs
// from
// https://csherratt.github.io/csherratt/blog/2013/11/24/matrix-multiply-in-rust/
struct Mat4 {
dat: [[f32; 4]; 4]
}
impl Mat4 {
pub fn mult_m(a: Mat4, b: &Mat4) -> Mat4
{
let mut out = Mat4 {
dat: [[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]
};
for i in 0..4 {
for j in 0..4 {
for k in 0..4 {
out.dat[i][j] += a.dat[i][k] * b.dat[k][j];
}
}
}
out
}
pub fn print(self)
{
for i in 0..4 {
for j in 0..4 {
print!("{} ", self.dat[i][j]);
}
print!("\n");
}
}
}
fn main()
{
let mut a = Mat4 {
dat: [[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]]
};
let b = Mat4 {
dat: [[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]]
};
for _ in 0..100_000 {
a = Mat4::mult_m(a, &b);
}
a.print();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment