Home > database >  How can I create a diagonal matrix in Eigen
How can I create a diagonal matrix in Eigen

Time:11-17

I was reading this post and when I was replicating it using

#include <iostream>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Dense>

int main(){
    Eigen::DiagonalMatrix<double, 3> M(3.0, 8.0, 6.0);
    std::cout << M << std::endl;
    return 0;
}

I get the error

error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'Eigen::DiagonalMatrix<double, 3>')
  std::cout << M << std::endl;
  ~~~~~~~~~ ^  ~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.0.sdk/usr/include/c  /v1/cstddef:143:3: note: candidate function template not viable: no known conversion from 'std::ostream' (aka 'basic_ostream<char>') to 'std::byte' for 1st argument
  operator<< (byte  __lhs, _Integer __shift) noexcept
  ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.0.sdk/usr/include/c  /v1/ostream:748:1: note: candidate function template not viable: no known conversion from 'Eigen::DiagonalMatrix<double, 3>' to 'char' for 2nd argument
operator<<(basic_ostream<_CharT, _Traits>& __os, char __cn)
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.0.sdk/usr/include/c  /v1/ostream:781:1: note: candidate function template not viable: no known conversion from 'Eigen::DiagonalMatrix<double, 3>' to 'char' for 2nd argument
operator<<(basic_ostream<char, _Traits>& __os, char __c)
^

and a few more lines like this. I complied it using the CMakeLists.txt file

cmake_minimum_required(VERSION 3.0)

project(ExternalLib CXX)

set(CMAKE_CXX_STANDARD 17)

find_package(Eigen3 REQUIRED)

add_executable(out main.cpp)
target_link_libraries(main PUBLIC)

Can anyone help me understand what might be the issue here? Thanks in advance!

CodePudding user response:

In order to print the matrix you have to cast your DiagonalMatrix to a DenseMatrixType, for example by doing:

std::cout << static_cast<Eigen::Matrix3d>(M) << std::endl;

Or by using the toDenseMatrix method:

std::cout << M.toDenseMatrix() << std::endl;
  • Related