2014-03-27 39 views
0

我需要在matlab中爲一個文件編寫一個矩陣(不同的大小),並從該文件中讀取該矩陣並存儲在一個數組中。 任何人都可以幫助我嗎?在Matlab中編寫一個大尺寸的矩陣,並在C++中讀取

使用保存我的txt文件矩陣在MATLAB:

dlmwrite('f:\ThetaR.txt', thetaPrim, 'delimiter', '\t','precision',4) // thetaPrim is the name of my matrix 

但我不能把它存放在C++。 如果採取矩陣以動態的方式要好得多然而這WY是不是工作壓力太大

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 ; 
} 

看到輸出:

screencap of a command window with a bunch of numbers in it

+0

您是如何嘗試讀取C++中的矩陣的?你有一些不起作用的代碼嗎? – remus

+0

'std :: ifstream','std :: getline' –

+0

@MattPhillips我已經嘗試過,但不工作,'ifstream in(「f:\\ ThetaR.txt」); if(!in){ std :: cout <<「無法打開文件。\ n」; return; (y = 0; y >距離[x] [y] }' – Jules

回答

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