gpt4 book ai didi

c++ - 在文本文件中打印矩阵

转载 作者:行者123 更新时间:2023-11-30 02:36:45 24 4
gpt4 key购买 nike

我想用 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();

关于c++ - 在文本文件中打印矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32381484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com