在文本文件中打印矩阵
Print a matrix in a text file
我想用 gnuplot 绘制 3D 图 (x,y,z)。
为了做到这一点,我想到了在 C++ 中使用 fstream 将矩阵写入文本文件,然后根据 this post 使用 splot 获取数据矩阵的 3D 图。
假设这是正确的方法,文本文件中的数据应如下所示:
x[1] x[2] x[3]
y[1] z[1][1] z[1][2] z[1][2]
y[2] z[2][1] z[1][2] z[2][3]
y[3] z[3][1] z[3][2] z[3][3]
为了得到矩阵我写了下面的代码:
fstream myfile;
myfile.open("example.txt",fstream::out);
//rows
for (int j=0; j< 3;j++)
{
myfile << x[j]<< std::endl;
}
//columns
for (int i=0; i< 3;i++)
{
myfile << y[i]<< std::endl;
}
//columns
for (int i=1; i< 3;i++)
{
//rows
for (int j=1; j< 3;j++)
{
myfile << z[i][j] << std::endl;
}
}
myfile.close();
我用这种方法得到了列中的所有内容,所以问题是如何打印矩阵?
这样的事情应该可行,(我假设您需要在矩阵的每个元素之间使用制表符,如果需要,输入逗号)
fstream myfile;
myfile.open("example.txt",fstream::out);
for (int j=0; j< 3;j++)// Prints row of x
{
myfile << x[j]<< "\t";
}
myfile<< std::endl;
for (int i=0; i< 3;i++) //This variable is for each row below the x
{
myfile << y[i]<< "\t";
for (int j=0; j<3;j++)
{
myfile << z[i][j] << "\t";
}
myfile<<std::endl;
}
myfile.close();
如果我没记错的话,你的循环没有很好地定义,你应该知道 std::endl 跳转到一个新行,这就是你得到 1 列的原因。
尝试:
for (int j=0; j< 3;j++){
myfile << x[j] <<"\t";
}
myfile<< std::endl;
for(int j=0 ; j<3 ; j++){
myfile << y[j]<<"\t";
for(int i=0;i<3;i++)
myfile << z[j]x[i]<<"\t";
myfile<< std::endl;
}
我想用 gnuplot 绘制 3D 图 (x,y,z)。
为了做到这一点,我想到了在 C++ 中使用 fstream 将矩阵写入文本文件,然后根据 this post 使用 splot 获取数据矩阵的 3D 图。
假设这是正确的方法,文本文件中的数据应如下所示:
x[1] x[2] x[3]
y[1] z[1][1] z[1][2] z[1][2]
y[2] z[2][1] z[1][2] z[2][3]
y[3] z[3][1] z[3][2] z[3][3]
为了得到矩阵我写了下面的代码:
fstream myfile;
myfile.open("example.txt",fstream::out);
//rows
for (int j=0; j< 3;j++)
{
myfile << x[j]<< std::endl;
}
//columns
for (int i=0; i< 3;i++)
{
myfile << y[i]<< std::endl;
}
//columns
for (int i=1; i< 3;i++)
{
//rows
for (int j=1; j< 3;j++)
{
myfile << z[i][j] << std::endl;
}
}
myfile.close();
我用这种方法得到了列中的所有内容,所以问题是如何打印矩阵?
这样的事情应该可行,(我假设您需要在矩阵的每个元素之间使用制表符,如果需要,输入逗号)
fstream myfile;
myfile.open("example.txt",fstream::out);
for (int j=0; j< 3;j++)// Prints row of x
{
myfile << x[j]<< "\t";
}
myfile<< std::endl;
for (int i=0; i< 3;i++) //This variable is for each row below the x
{
myfile << y[i]<< "\t";
for (int j=0; j<3;j++)
{
myfile << z[i][j] << "\t";
}
myfile<<std::endl;
}
myfile.close();
如果我没记错的话,你的循环没有很好地定义,你应该知道 std::endl 跳转到一个新行,这就是你得到 1 列的原因。 尝试:
for (int j=0; j< 3;j++){
myfile << x[j] <<"\t";
}
myfile<< std::endl;
for(int j=0 ; j<3 ; j++){
myfile << y[j]<<"\t";
for(int i=0;i<3;i++)
myfile << z[j]x[i]<<"\t";
myfile<< std::endl;
}