How to implement matrix multiplication in Rust

1 Answer

0 votes
// Multiply rows of A by columns of B.

type Matrix = Vec<Vec<i32>>;

// Print a 2D array (matrix)
fn print_matrix(arr2d: &Matrix) {
    for row in arr2d {
        for val in row {
            print!("{:4}", val);
        }
        println!();
    }
}

// Multiply matrices A and B into C
fn multiple_matrix(a: &Matrix, b: &Matrix, c: &mut Matrix) {
    for i in 0..c.len() {
        for j in 0..c[i].len() {
            for k in 0..a[i].len() {
                c[i][j] += a[i][k] * b[k][j];
            }
        }
    }
}

fn main() {
    // Create matrices
    let a: Matrix = vec![
        vec![1, 8, 5],
        vec![6, 7, 1],
        vec![8, 7, 6],
    ];

    let b: Matrix = vec![
        vec![4, 8, 1],
        vec![6, 5, 3],
        vec![4, 6, 5],
    ];

    // Initialize result matrix C with zeros
    let mut c: Matrix = vec![vec![0; b[0].len()]; a.len()];

    // c[0][0] = (a[0][0] * b[0][0]) + (a[0][1] * b[1][0]) + (a[0][2] * b[2][0])

    print_matrix(&a);
    println!();
    print_matrix(&b);
    println!();

    multiple_matrix(&a, &b, &mut c);

    print_matrix(&c);
}



/*
run:
        
     1   8   5
     6   7   1
     8   7   6
    
     4   8   1
     6   5   3
     4   6   5
    
    72  78  50
    70  89  32
    98 135  59
    
*/

 



answered May 25 by avibootz
...