有没有办法在 gdb 中打印犰狳矩阵?

2021-12-19 00:00:00 matrix debugging gdb c++ armadillo

我正在使用 gdb 来调试我的 C++ 程序.我正在使用犰狳数值库来定义我的矩阵.我有一个像这样定义的犰狳矩阵:

I'm using gdb to debug my c++ program. I'm using the armadillo numerical library to define my matrices. I have an armadillo matrix defined like so:

mat A = randu<mat>(5,5);

是否可以在使用 gdb 调试器时打印整个矩阵?

Is it possible to print the whole matrix while using the gdb debugger?

推荐答案

这个问题可能很老了,但我对它的磕磕绊绊让我找到了适合自己工作的解决方案.

The question may be old, but stumbling over it made me find a solution for my own work.

由于 Armadillo 库基于模板的性质,您需要提供一些自己的帮助程序:

Due to the template-based nature of the Armadillo library you need to provide some helpers of your own:

#include <iostream>
#include <armadillo>

template<class Matrix>
void print_matrix(Matrix matrix) {
    matrix.print(std::cout);
}

//provide explicit instantiations of the template function for 
//every matrix type you use somewhere in your program.
template void print_matrix<arma::mat>(arma::mat matrix);
template void print_matrix<arma::cx_mat>(arma::cx_mat matrix);

int main() {
    arma::mat matrix = arma::randu(10,10);

    return 0;
}

现在您可以轻松地从 gdb 中调用 print_matrix:

Now you can easily call print_matrix from within gdb:

(gdb) call print_matrix<arma::Mat<double> >(matrix) 
   0.8402   0.4774   0.0163   0.5129   0.5267   0.5260   0.2383   0.5316   0.6879   0.9565
   0.3944   0.6289   0.2429   0.8391   0.7699   0.0861   0.9706   0.0393   0.1660   0.5886
   0.7831   0.3648   0.1372   0.6126   0.4002   0.1922   0.9022   0.4376   0.4401   0.6573
   0.7984   0.5134   0.8042   0.2960   0.8915   0.6632   0.8509   0.9318   0.8801   0.8587
   0.9116   0.9522   0.1567   0.6376   0.2833   0.8902   0.2667   0.9308   0.8292   0.4396
   0.1976   0.9162   0.4009   0.5243   0.3525   0.3489   0.5398   0.7210   0.3303   0.9240
   0.3352   0.6357   0.1298   0.4936   0.8077   0.0642   0.3752   0.2843   0.2290   0.3984
   0.7682   0.7173   0.1088   0.9728   0.9190   0.0200   0.7602   0.7385   0.8934   0.8148
   0.2778   0.1416   0.9989   0.2925   0.0698   0.4577   0.5125   0.6400   0.3504   0.6842
   0.5540   0.6070   0.2183   0.7714   0.9493   0.0631   0.6677   0.3540   0.6867   0.9110

多亏了制表符补全,您只需要实际键入print_matrix的几个字符.>.

Thanks to tab completion you only need to actually type a few characters of print_matrix<arma::Mat<double> >.

相关文章