2013-03-29 277 views
0

我用這個:如何使用textscan在Matlab中讀取多行?

weights=fopen('indices.txt'); 
weights=textscan(weights, '%d %d %d %d %d %d %d') 

但這只是我的讀取文件的第一行。 我的文件看起來像這樣:

0 90 100 5 0 0 0 (class) 
19 5 0 0 0 0 0 (class2) 
5 5 0 0 0 0 0 (class3) 
-10 -5 0 0 0 0 0 (class4) 

而且我也不需要在括號什麼

非常感謝!

回答

2

對於這種情況,你可以做到以下幾點:

fid = fopen('indices.txt'); 
num_ints = 7; 
num_rows = 4; 

format = [repmat('%d ', 1, num_ints), '%s']; 
weights = textscan(fid, format, num_rows); 
weights = [weights{1:num_ints}]; 
fclose(fid); 

當然缺點是,你必須知道你事先閱讀的行數。你可以嘗試在一個循環中調用textscan,但這似乎並不是它如何使用(如果我試圖逐行讀取文件,我寧願使用fgetl)。

1

使用以下命令:

fh = fopen('indices.txt'); 
resC = textscan(fh, '%d %d %d %d %d %d %d %s', 1000); 
res = cell2mat(resC(1:7)) 
fclose(fh); 

textscan將只讀取(和返回)到線路的可用數量。但請注意,textscan會爲您提供的行數(此處爲1000)分配內存,因此您要在那裏選擇「明智」的內容。