简体   繁体   中英

How can I print a diagonal matrix in Eigen

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM