How to multiply a RealVector by a RealMatrix?

2019-05-23 07:52发布

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条回答
够拽才男人
2楼-- · 2019-05-23 08:21

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}

查看更多
登录 后发表回答