How to convert Eigen library's Matrix or Vector types to string?
Asked Answered
A

3

9

How to get text representation for Vector3f or other types in Eigen library. I see lot of examples that uses .format() which returns WithFormat class. This then can be used with cout. However I'm looking for way to get Vector3f as std:string in some human readable form. Exact formatting isn't too important so if Eigen has any default formatting then that works as well.

Note: I can certainly use stringstream to replace cout but I'm hopping there is more direct way to do this.

Aylesbury answered 29/5, 2016 at 9:0 Comment(0)
A
0

The approach I finally took is as follows:

static std::string toString(const Vector3d& vect)
{
    return stringf("[%f, %f, %f]", vect[0], vect[1], vect[2]);
}

static string stringf(const char* format, ...)
{
    va_list args;
    va_start(args, format);

    int size = _vscprintf(format, args) + 1;
    std::unique_ptr<char[]> buf(new char[size] ); 

    #ifndef _MSC_VER
        vsnprintf(buf.get(), size, format, args);
    #else
        vsnprintf_s(buf.get(), size, _TRUNCATE, format, args);
    #endif

    va_end(args);            

    return string(buf.get());
}
Aylesbury answered 13/10, 2016 at 20:19 Comment(1)
Given the built-in streaming operators, this does not seem like the right way to go. Even without the built-in stream operators, this is not a good way to go ("new"ing the char array? really?).Airworthy
R
14

The easiest solution I found out, not sure if optimal, is:

static std::string toString(const Eigen::MatrixXd& mat){
    std::stringstream ss;
    ss << mat;
    return ss.str();
}
Renaerenaissance answered 17/5, 2018 at 17:18 Comment(0)
B
2

As far as I know, the stringstream method is the way to go. In fact, in the IO.h file (Eigen::internal::print_matrix) the developers use stringstreams to obtain the width of each entry.

Bathysphere answered 29/5, 2016 at 9:50 Comment(0)
A
0

The approach I finally took is as follows:

static std::string toString(const Vector3d& vect)
{
    return stringf("[%f, %f, %f]", vect[0], vect[1], vect[2]);
}

static string stringf(const char* format, ...)
{
    va_list args;
    va_start(args, format);

    int size = _vscprintf(format, args) + 1;
    std::unique_ptr<char[]> buf(new char[size] ); 

    #ifndef _MSC_VER
        vsnprintf(buf.get(), size, format, args);
    #else
        vsnprintf_s(buf.get(), size, _TRUNCATE, format, args);
    #endif

    va_end(args);            

    return string(buf.get());
}
Aylesbury answered 13/10, 2016 at 20:19 Comment(1)
Given the built-in streaming operators, this does not seem like the right way to go. Even without the built-in stream operators, this is not a good way to go ("new"ing the char array? really?).Airworthy

© 2022 - 2024 — McMap. All rights reserved.