2015-09-03 151 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; 
}