>> m = np.eye(3) >>> v = np.array([1, 2, 3]) >>> m * v # Or" /> >> m = np.eye(3) >>> v = np.array([1, 2, 3]) >>> m * v # Or" /> >> m = np.eye(3) >>> v = np.array([1, 2, 3]) >>> m * v # Or"/>

Multiply matrix by vector row-wise

126 views Asked by At

How can I multiply a matrix and a vector "row-wise" in nalgebra? Like I would do in numpy

>>> m = np.eye(3)
>>> v = np.array([1, 2, 3])
>>> m * v  # Or v * m
# Gives [[1, 0, 0],
#        [0, 2, 0],
#        [0, 0, 3]]

What I tried:

  • dot is doing the "real" math operation (outputting a vector)
  • m * v or v * m doesn't work because it wants either 2 matrices or 2 vectors
  • component_mul requires the same number of elements

Note: I know that I can convert my vector into a matrix and use other operations, but my goal is to avoid useless work.

1

There are 1 answers

0
Kaplan On

You would need to know what numpy calulates. In both cases v * m or m * v, if I multiply a vector by the identity matrix, the result is that vector:
eg. [1.0, 2.0, 3.0]

let m = DMatrix::<f32>::identity(3, 3);
let v = DMatrix::<f32>::from_row_slice(1, 3, &[1.0, 2.0, 3.0]);
println!("{:?}", v * m);
let m = DMatrix::<f32>::identity(3, 3);
let v = DMatrix::<f32>::from_row_slice(3, 1, &[1.0, 2.0, 3.0]);
println!("{:?}", m * v);

The straight-forward method to write the vector elements directly into the matrix would only need one loop:

let mut m = DMatrix::<f32>::zeros(3, 3);
let mut pos = 0;
for n in [1.0, 2.0, 3.0] {           //[[1, 0, 0],
    m.get_mut(pos).map(|f| *f = n);  // [0, 2, 0],
    pos += 4;  // rows + 1           // [0, 0, 3]]
}
println!("{:?}", m);