How to multiply a RealVector by a RealMatrix?

余生颓废 提交于 2019-12-22 17:42:18

问题


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}



来源:https://stackoverflow.com/questions/33275669/how-to-multiply-a-realvector-by-a-realmatrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!