我需要在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 ;
}
看输出:
答案 0 :(得分:0)
很难看到捆绑在一起的double语句,但外部for循环的结束大括号丢失了。增加了三条评论以帮助理解。修改后的代码:
//
// 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