2015-09-03 131 views
1

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

我以这种方式在列中获取所有内容,所以问题是如何打印矩阵?

+0

你真的需要更好的[缩进风格(https://en.wikipedia.org/wiki/Indent_style) – NathanOliver

+1

你知道,在C++的索引从0开始? – v010dya

回答

2

像这样的事情应该工作,(我假设你需要的标签矩阵中的每个元素之间,输入逗号如果需要的话)

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(); 
+0

谢谢..z [0] [0]是空的。这就是为什么我写了三个循环。 – Jack

+0

你的意思是说你的索引从z [1] [1]和x [1]和y [1]开始?因为在C++中,它们从0 – 7VoltCrayon

+0

z [1] [1]开始,但是从x [0]和y [0]开始。我在上面的问题中显示了矩阵。所以我想“\ t”就是我一直想念的东西。那么有没有办法拥有一个空插槽? – Jack

0

如果我没有记错的话,你的循环是不是很定义良好,你应该知道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; 
}