matrixvectorrustnalgebra

How do I calculate inner product of two vectors in nalgebra?


From the following

let v = OVector::<f64, U2>::from_column_slice(&[3_f64, 4_f64]);
let x = &v.transpose() * &v;        // get the inner product, i.e. <v,v>

I expected x to be a f64 scalar, i.e. x = 25.0.

But actually, I can only obtain x as OMatrix::<f64, Cosnt<1>, Const<1>>.

The case can be even worse in matrix product operations. for example, the following code doesn't work since v^T v is not a scalar.

let m = OMatrix::<f64, U2, U2>::from_element(1.0);
let v = OVector::<f64, U2>::from_column_slice(&[3_f64, 4_f64]);

// not working
let y = &v.transpose() * &v * m;        // types conflict 

// working
let y = 25.0 * m;                       // expected to behave like this

What is the correct way to do this?


Solution

  • Usually, in maths, you would identify 1x1 matrices with scalars (because, for some definition of being equivalent, they are equivalent...). When doing this, the dot product of two vectors is exactly the dot product between two matrices, when we see vectors as matrix columns (which are also equivalent for some equivalence...).

    However, here, it is not the case: Rust has to know what is the type of the data. So, I would suggest, since you are using matrices to start with, to use the actual matrix dot product, not the vector one. It's simply (v.transpose()*v).trace(). This is a more general dot product, but notice taking the trace will exactly "extract" the scalar from the 1x1 matrix.

    Otherwise, this operation is already defined as the dot product (unsurprisingly): v.dot(v).