Print matlab matrix as eigen matrix

Alec Jacobson

January 01, 2021

weblog/

print_eigen = @(A,name) fprintf(['Eigen::Matrix<double,%d,%d> %s = (Eigen::Matrix<double,%d,%d>(%d,%d)<<' sprintf([repmat('%g,',[1,size(A,2)])],A') '\b).finished();\n'],size(A),name,size(A),size(A))

then

M = magic(3);
print_eigen(M,'M')

produces

Eigen::Matrix<double,3,3> M = (Eigen::Matrix<double,3,3>(3,3)<<8,1,6,3,5,7,4,9,2).finished();