Reputation: 569
Let's assume that we have a 10x20 real matrix:
Eigen::MatrixXd A(10,20);
A.setRandom();
We would like to construct a 10x10 matrix of the form
B = [v v ... v v]
where v
is a column vector of length 10
. For this vector, v
, each element is the squared norm of each row of A, that is:
v = ( ||x_1||^2, ||x_2||^2, ..., ||x_10||^2,)^T
,
where x_j
denotes the j-th row of A.
What is the most efficient way to construct matrix B
?
I could construct v
as follows:
Eigen::VectorXd v(10);
for (int i=1; i<10; i++)
{
v(i) = A.row(i).squaredNorm();
}
I think that this step cannot be solved without a for
loop. How could I replicate this column 10 times such that B
is filled as discussed above?
Upvotes: 2
Views: 6458
Reputation: 10596
Your assumption is wrong. The loop can be avoided by doing a rowwise
operation. Then, the replication can be done as follows.
#include <iostream>
#include <Eigen/Core>
int main ()
{
Eigen::MatrixXd A(10,20), B, C;
A.setRandom();
Eigen::VectorXd v(10);
v = A.rowwise().squaredNorm();
B = v.replicate(1,10);
std::cout << B << "\n\n";
return 0;
}
It can also be written in a single line as
B = A.rowwise().squaredNorm().replicate(1,10);
I highly recommend reading the documentation. It's pretty well written.
Upvotes: 6