【问题标题】:write a big size Matrix in Matlab and read in C++在 Matlab 中编写一个大尺寸矩阵并在 C++ 中读取
【发布时间】:2025-12-19 10:05:12
【问题描述】:

我需要在 matlab 中将一个矩阵(不同大小)写入一个文件,然后在 c++ 中从该文件中读取该矩阵并存储在一个数组中。 谁能帮帮我?

在matlab的txt文件中保存了我的矩阵:

dlmwrite('f:\ThetaR.txt', thetaPrim, 'delimiter', '\t','precision',4) // thetaPrim is the name of my matrix

但我不能将它存储在 C++ 中。 如果采用动态矩阵的方式要好得多,但是这种方式也行不通

float thetaR [i][j];
ifstream in("f:\\ThetaR.txt"); 
if (!in) { std::cout << "Cannot open file.\n"; return; } 
for (y = 0; y < j; y++)  { 
    for (x = 0; x < i; x++)  {    
        in >> theta[x][y];  
    }

我也将矩阵显示为字符串,但我如何拆分它们,因为它们之间没有字母

这是代码:

ifstream in("f:\\ThetaR.txt");

if (!in) {
    std::cout << "Cannot open file.\n";
    return;   
}

std::string line;

while (std::getline(in, line)) {
    std::istringstream iss(line);
    std::cout << line ; 
}

查看输出:

【问题讨论】:

  • 您是如何尝试在 C++ 中读取矩阵的?你有一些不起作用的代码吗?
  • std::ifstream, std::getline
  • @MattPhillips 我试过但没用,` ifstream in("f:\\ThetaR.txt"); if (!in) { std::cout > 距离[x][y]; }`
  • 是否可以直接从文件中读取并保存到数组中?
  • 如果这是您在上面评论中的代码,请编辑问题,添加代码。我们其他人会更容易审查。代码一定要缩进四个空格,这样SO系统会自动美化帖子。

标签: c++ matlab file matrix


【解决方案1】:

很难看到捆绑在一起的双 for 语句,但是缺少外部 for 循环的右花括号。增加了三个cmets来帮助理解。修改代码:

//
// Assumed that i and j have valid values before using them below.
// If not, then the thetaR array will not have any of the expected data
// and the double for loop will not behave as expected.  Hence, no data
// will be read and/or memory overruns and/or undefined behavior and/or
// application crash.
//
float thetaR [i][j];

ifstream in("f:\\ThetaR.txt"); 
if (!in) 
{ 
  std::cout << "Cannot open file.\n"; 
  return; 
} 

for (y = 0; y < j; y++)  
{ 
  for (x = 0; x < i; x++)  
  {    
     in >> thetaR[x][y];  // Added the R to the array variable name
  }
} // added this to close outer for loop

【讨论】: