您的位置:首页 > 其它

Lesson 7 Matrix-matrix and matrix-vector multiplication

2015-11-02 21:08 399 查看
Matrix-matrix multiplication is again done with 
operator*
. Since vectors are a special case of matrices, they are implicitly handled there too, so matrix-vector product is really just a special case of matrix-matrix product, and so is vector-vector
outer product. Thus, all these cases are handled by just two operators:
binary operator * as in 
a*b

compound operator *= as in 
a*=b
 (this multiplies on the right: 
a*=b
 is equivalent to 
a = a*b
)
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
int main()
{
Matrix2d mat;
mat << 1, 2,
3, 4;
Vector2d u(-1,1), v(2,0);
std::cout << "Here is mat*mat:\n" << mat*mat << std::endl;
std::cout << "Here is mat*u:\n" << mat*u << std::endl;
std::cout << "Here is u^T*mat:\n" << u.transpose()*mat << std::endl;
std::cout << "Here is u^T*v:\n" << u.transpose()*v << std::endl;
std::cout << "Here is u*v^T:\n" << u*v.transpose() << std::endl;
std::cout << "Let's multiply mat by itself" << std::endl;
mat = mat*mat;
std::cout << "Now mat is mat:\n" << mat << std::endl;
}


Note: if you read the above paragraph on expression templates and are worried that doing 
m=m*m
 might cause aliasing issues, be reassured for now: Eigen treats
matrix multiplication as a special case and takes care of introducing a temporary here, so it will compile 
m=m*m
 as:

tmp = m*m;

m = tmp;

If you know your matrix product can be safely evaluated into the destination matrix without aliasing issue, then you can use the noalias() function
to avoid the temporary, e.g.:

c.noalias() += a * b;

For more details on this topic, see the page on aliasing.

Note: for BLAS users worried about performance, expressions such as 
c.noalias() -= 2 * a.adjoint() * b;
 are fully optimized and trigger a single gemm-like function call.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: