我正在尝试在Mac OS上运行犰狳,但不断收到相同的错误



我正在尝试用文本文件中的数据填充矩阵。

这是我的代码

int main() {
ifstream in;

int n=150;
int m=5;

mat coordinates (n,m);
coordinate.zeros();
in.open("test.txt");
for (int i=0; i<n ; i++) {
    for (int j=0; i<m ; j++)
        in >> coordinates(i,j);
  return 0;
}

我用comand编译了它

g++ -I/usr/local/include coordinates.cpp -O2 -larmadillo -llapack -lblas

到目前为止一切似乎都很好,但当我尝试运行程序时,我得到了以下错误

error: Mat::operator(): index out of bounds libc++abi.dylib: terminating with uncaught exception of type std::logic_error: Mat::operator(): index out of bounds Abort trap: 6

我想尽一切办法,但都无济于事。你有什么建议吗?

谢谢你抽出时间。

您的代码中有一个错误:第二个循环有i<m而不是j<m

此外,不要将>>运算符直接用于矩阵,因为您无法检查元素是否被实际读取。相反,您可以使用.load()成员函数简单地加载整个文件。

在发布基本问题之前,最好先彻底阅读Armadillo文档。

// simple way
mat coordinates;
coordinates.load("test.txt", raw_ascii);   // .load() will set the size
coordinates.print();  

// complicated way
ifstream in;
in.open("test.txt");
unsigned int n=150;
unsigned int m=5;
mat coordinates(n, m, fill::zeros);
for(unsigned int i=0; i<n; ++i)
    {
    for(unsigned int j=0; j<m; ++j)
        {
        double val;
        in >> val;
        if(in.good())  { coordinates(i,j) = val; }
        }
    }
coordinates.print();

最新更新