Your answer is one click away!

nullgeppetto February 2016
### Replicate a column VectorXd in order to construct a MatrixXd in Eigen, C++

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?

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.

Asked in February 2016

Viewed 2,717 times

Voted 14

Answered 1 times

Viewed 2,717 times

Voted 14

Answered 1 times