问题描述
我需要使用本征C ++库将每个矩阵列乘以每个矢量元素.我尝试了colwise,但没有成功.
I need to multiply each matrix column by each vector element using Eigen C++ library. I tried colwise without success.
样本数据:
Eigen::Matrix3Xf A(3,2); //3x2
A << 1 2,
2 2,
3 5;
Eigen::Vector3f V = Eigen::Vector3f(2, 3);
//Expected result
C = A.colwise()*V;
//C
//2 6,
//4 6,
//6 15
//this means C 1st col by V first element and C 2nd col by V 2nd element.
矩阵A可以具有3xN和V Nx1.含义(列数x行数).
Matrix A can have 3xN and V Nx1. Meaning (cols x rowls).
推荐答案
这就是我要做的:
Eigen::Matrix3Xf A(3, 2); // 3x2
A << 1, 2, 2, 2, 3, 5;
Eigen::Vector3f V = Eigen::Vector3f(1, 2, 3);
const Eigen::Matrix3Xf C = A.array().colwise() * V.array();
std::cout << C << std::endl;
示例输出:
1 2
4 4
9 15
说明
您接近了,诀窍是使用.array()
进行广播乘法.
Explanation
You were close, the trick is to use .array()
to do broadcasting multiplications.
colwiseReturnType
没有.array()
方法,因此我们必须在A的数组视图上进行逐级提示.
colwiseReturnType
doesn't have a .array()
method, so we have to do our colwise shenanigans on the array view of A.
如果要计算两个向量的按元素乘积(最酷的猫称之为 Hadamard产品),您可以这样做
If you want to compute the element-wise product of two vectors (The coolest of cool cats call this the Hadamard Product), you can do
Eigen::Vector3f a = ...;
Eigen::Vector3f b = ...;
Eigen::Vector3f elementwise_product = a.array() * b.array();
以上代码以列方式执行的操作.
Which is what the above code is doing, in a columnwise fashion.
要解决行的情况,您可以使用.rowwise()
,并且需要额外的transpose()
来使之适合
To address the row case, you can use .rowwise()
, and you'll need an extra transpose()
to make things fit
Eigen::Matrix<float, 3, 2> A; // 3x2
A << 1, 2, 2, 2, 3, 5;
Eigen::Vector2f V = Eigen::Vector2f(2, 3);
// Expected result
Eigen::Matrix<float, 3, 2> C = A.array().rowwise() * V.transpose().array();
std::cout << C << std::endl;
示例输出:
2 6
4 6
6 15
这篇关于使用Eigen C ++库将每个矩阵列乘以每个向量元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!