'Eigen3 library with C++20 format

I am trying to print Eigen::Array or Eigen::Matrix with c++20 format, instead of Eigen::IOFormat. I would like to control the precision and alignment of elements in the matrix with specifiers, for example,

#include <Eigen/Core>
#include <format>
#include <iostream>

int main()
{
    Eigen::ArrayXXd mat( 3, 4 );
    mat.setZero();
    std::cout << std::format( "mat={:9.4f}\n", mat );
    return 0;
}

How can I get the following expected result?

mat=   0.0000   0.0000   0.0000   0.0000
       0.0000   0.0000   0.0000   0.0000
       0.0000   0.0000   0.0000   0.0000


Solution 1:[1]

You may look at https://gite.lirmm.fr/rpc/utils/eigen-fmt and see if it helps you out.

You basically need to include this header file in order to have eigen support for print/format using the fmt library. Since std::format was based from fmt, that code should be a good start in order to achieve what you want. Note that you may need to make a few adjustments.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 A. Soprana