How to multiply two matrices in Rust

1 Answer

0 votes
use ndarray::array;
use ndarray::Array2;

fn main() {
    let matrix1 = array![
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ];
    
    let matrix2 = array![
        [4, 6],
        [7, 3],
        [1, 2]
    ];
    
    let multiplication: Array2<i32> = matrix1.dot(&matrix2);

    println!("{:?}", multiplication);

    let (rows, cols) = multiplication.dim(); // Use dim() to get dimensions

    for i in 0..rows {
        for j in 0..cols {
            print!("{:?} ", multiplication.get((i, j)).unwrap()); // Use get() or at()
        }
        println!();
    }
}

 
      
/*
run:
   
[[21, 18],
 [57, 51],
 [93, 84]], shape=[3, 2], strides=[2, 1], layout=Cc (0x5), const ndim=2
21 18 
57 51 
93 84
     
*/

 



answered Mar 4, 2025 by avibootz
...