Vit
Vit

Reputation: 21

Eigen: Zero matrix with smaller matrix as the "diagonals"

Is it possible to create a 9x9 matrix where the "diagonal" is another matrix and the rest are zeroes, like this:

5 5 5 0 0 0 0 0 0
5 5 5 0 0 0 0 0 0
5 5 5 0 0 0 0 0 0
0 0 0 5 5 5 0 0 0
0 0 0 5 5 5 0 0 0
0 0 0 5 5 5 0 0 0
0 0 0 0 0 0 5 5 5
0 0 0 0 0 0 5 5 5
0 0 0 0 0 0 5 5 5

from a smaller 3x3 matrix repeated:

5 5 5
5 5 5
5 5 5

I am aware of the Replicate function but that repeats it everywhere in the matrix and doesn't maintain the zeroes. Is there a builtin way of achieving what I'm after?

Upvotes: 0

Views: 111

Answers (2)

chtz
chtz

Reputation: 18807

You can use the (unsupported) KroneckerProduct module for that:

#include <unsupported/Eigen/KroneckerProduct>
int main()
{
    Eigen::MatrixXd A = Eigen::kroneckerProduct(Eigen::Matrix3d::Identity(), Eigen::Matrix3d::Constant(5));
    std::cout << A << '\n';
}

Upvotes: 0

Vit
Vit

Reputation: 21

One way of doing this is by using blocks where .block<3,3>(0,0) is a 3x3 block starting at 0,0. (Note: Your IDE might flag this line as an error but it will compile and run)

for (int x=0, x<3, x++){
    zero_matrix.block<3,3>(x*3,x*3) = five_matrix;
}

Upvotes: 2

Related Questions