如何在c++中使用eigen库导入矩阵市场文件

问题描述 投票:0回答:4

我是 C++ 新手,习惯使用 MATLAB。不幸的是,我的矩阵大小对于 MATLAB 来说太大了,所以我想在 C++ 中尝试一下。 我找到了 eigen 库 3.3.7 来进行矩阵操作。为此,我需要将矩阵市场文件导入 Visual Studio 2019。我了解 C++ 的一些基础知识,并尝试使用 loadMarket 导入我的文件。尝试编译后,我在 MarketIO.h 文件中发现了大约 30 个错误。

这是我正在使用的文件。 https://eigen.tuxfamily.org/dox/unsupported/MarketIO_8h_source.html

#include <Eigen/Sparse>
#include <unsupported/Eigen/src/SparseExtra/MarketIO.h>

int main(){
    typedef Eigen::SparseMatrix<float, Eigen::RowMajor>SMatrixXf;
    SMatrixXf A;
    Eigen::loadMarket(A, "B.mtx");
}
c++ sparse-matrix eigen file-import
4个回答
2
投票

您绝不能直接包含来自

unsupported/Eigen/src/...
(或来自
Eigen/src/...
)的文件。只需包含相应的父标头即可:

#include <unsupported/Eigen/SparseExtra>

0
投票

在使用问题中的

SparseExtra
模块时,我可能遇到了相同的问题或密切相关的问题(不幸的是,该问题没有详细的错误消息)。

通过编译问题中提供的代码,我收到许多错误,其中:

/usr/include/eigen3/unsupported/Eigen/src/SparseExtra/MarketIO.h:115:20: 
error: variable ‘std::ifstream in’ has initializer but incomplete type
  115 |   std::ifstream in(filename.c_str(),std::ios::in);
      |                    ^~~~~~~~

.... many warnings and errors releated to std::ifstream and std::ofstream ...

/usr/include/eigen3/unsupported/Eigen/src/SparseExtra/MarketIO.h:272:9: 
error: no match for ‘operator<<’ (operand types are ‘std::ofstream’ {aka 
‘std::basic_ofstream<char>’} and ‘const char [42]’)

使用

g++ -std=c++17
、g++ 版本 12.1.0、Eigen3 v 3.3

编译

我不知道这是否是一个 Eigen bug,但正如上面错误中的第一行所示,编译器似乎无法弄清楚

std::ifstream
的定义。

通过修改

MarketIO.h
源代码(在我的机器上位于
usr/include/eigen3/unsupported/Eigen/src/SparseExtra/MarketIO.h
)可以解决问题,如下所示:

// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2011 Gael Guennebaud <[email protected]>
// Copyright (C) 2012 Desire NUENTSA WAKAM <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_SPARSE_MARKET_IO_H
#define EIGEN_SPARSE_MARKET_IO_H

#include <iostream>
#include <vector>
#include <fstream>  // IMPORT THIS HEADER FILE!

... // no changes in the rest of the file

这将消除任何错误并使代码能够编译并正确加载矩阵。


0
投票

由于OP提到了大型矩阵,另一个选择是fast_matrix_marketEigen绑定。 Eigen 的

MarketIO.h
加载器是顺序的,fast_matrix_market 是并行的。

#include <fstream>
#include <Eigen/Sparse>
#include <fast_matrix_market/app/Eigen.hpp>

int main(){
    typedef Eigen::SparseMatrix<float, Eigen::RowMajor>SMatrixXf;
    SMatrixXf A;

    std::ifstream file("B.mtx");
    fast_matrix_market::read_matrix_market_eigen(file, A);
}

0
投票

请注意,

Eigen::loadMarket
的实现很简单,并且不支持对称性。请参阅此处文档

如果您的

.mtx
是对称的(格式以第一行以
%%MatrixMarket
开头),这只会加载一半,不会为您填充另一半。

考虑使用 fast_matrix_marketmatrix-market

© www.soinside.com 2019 - 2024. All rights reserved.