matrixrustmatrix-multiplicationnalgebra

Similar function to numpy.dot with nalgebra in Rust


I recently started to use nalgebra, but I can't for the life of me figure out how to do a regular dot product, like below:

dot product of two matricies

This is similar to how in Python, you can do this:

import numpy as np

arr1 = np.array([[1, 2, 3], [4, 5, 6]])
arr2 = np.array([[7, 8], [9, 10], [11, 12]])

print(arr1.dot(arr2)) # [[ 58  64][139 154]]

But when I do this in Rust with nalgebra, I get the wrong result:

let matrix1 = Matrix3x2::from_vec(vec![1, 2, 3, 4, 5, 6]);
let matrix2 = Matrix2x3::from_vec(vec![7, 8, 9, 10, 11, 12]);

println!("{:?}", matrix1); // [[1, 2, 3], [4, 5, 6]] 
println!("{:?}", matrix2); // [[7, 8], [9, 10], [11, 12]]
println!("{:?}", matrix1 * matrix2); // [[39, 54, 69], [49, 68, 87], [59, 82, 105]]

I also tried other functions like mul, cross, and dot, and all of them either didn't even work on these matrices or gave the wrong answer.

What am I missing here?


Solution

  • You've switched the matrix dimensions: your matrix1 is a Matrix3x2, which means it has 3 rows and 2 columns and similarly matrix2 has 2 rows and 3 columns.

    Try it with:

    let matrix1 = Matrix2x3::new(1, 2, 3, 4, 5, 6);
    let matrix2 = Matrix3x2::new(7, 8, 9, 10, 11, 12);
    

    Note that from_vec constructs a matrix in column-major order. If your data comes from a vector in row-major order, you will need to use from_row_slice.