Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,849 questions

55,678 answers

573 users

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
...