How to multiply a RealVector by a RealMatrix?

2019-05-23 07:56发布

问题:

How can I multiply a given RealVector by a RealMatrix? I can't find any "multiply" method on both classes, only preMultiply but it seems not work:

// point to translate
final RealVector p = MatrixUtils.createRealVector(new double[] {
        3, 4, 5, 1
});

// translation matrix (6, 7, 8)
final RealMatrix m = MatrixUtils.createRealMatrix(new double[][] {
        {1, 0, 0, 6},
        {0, 1, 0, 7},
        {0, 0, 1, 8},
        {0, 0, 0, 1}
});

// p2 = m x p
final RealVector p2 = m.preMultiply(p);
// prints {3; 4; 5; 87}
// expected {9; 11; 13; 1}
System.out.println(p2);

Please compare the actual result with the expected result.

Is there also a way for multiplying a Vector3D by a 4x4 RealMatrix where the w component is throw away? (I'm looking not for custom implementation but an already existing method in the library).

回答1:

preMultiply does not give you m x p but p x m. This would be suitable for your question but not for your comment // p2 = m x p.

To get the result you want you have two options:

  1. Use RealMatrix#operate(RealVector) which produces m x p:

    RealVector mxp = m.operate(p);    
    System.out.println(mxp);    
    
  2. Transpose the matrix before pre-multiplying:

    RealVector pxm_t = m.transpose().preMultiply(p);
    System.out.println(pxm_t);
    

Result:

{9; 11; 13; 1}