0

我有一些 .txt 文件如下所示:

1050.00 68.13

1048.00 67.89

1046.00 67.62

1044.00 67.30

1042.00 66.91

[ ... ]

我想将它乘以另一个矩阵。

我的问题是我不知道如何读取这些数据并将其存储在矩阵中。

有没有人有任何可以帮助我的想法?

4

3 回答 3

3

我将数据存储在 avector<vector<double>>中,并使用std::getlinestd::istringstreamoperator>>.

#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iterator>
#include <algorithm>
struct Matrix {
  std::vector<std::vector<double> > data;
  Matrix(const std::string& filename) {
    std::ifstream inFile(filename.c_str());
    std::string inLine;
    while(std::getline(inFile, inLine)) {
      std::istringstream inLineStream(inLine);
      std::vector<double> inLineData(
        (std::istream_iterator<double>(inLineStream)),
        std::istream_iterator<double>());
      data.push_back(inLineData);
    }
  }
  Matrix operator*(const Matrix& rhs) { ... };
};

int main () {
  Matrix a("a.txt");
  Matrix b("b.txt");
  Matrix c(a * b);
}
于 2012-05-03T15:18:29.867 回答
0

你可以这样读:

char *fname = "matrix.txt";
ifstream infile(fname);

float f;
while (infile >> f) {
   //store f to matrix
}

网上有很多maxtrix类的实现示例,有一个: http: //www.codeproject.com/Articles/3613/A-generic-reusable-and-extendable-matrix-class

于 2012-05-03T15:14:26.917 回答
0

什么是“矩阵”?

如果您有某种“矩阵库”,只需使用它的功能。

如果您自己实现矩阵,请逐行读取文本文件 (fgets()) 并使用 sscanf() 读取项目。

希望这可以帮助。

于 2012-05-03T15:12:03.753 回答