2015-09-02 91 views
0

我有以下格式的文本文件:格式化利用MATLAB讀取的fscanf

Row: 001, rank: 6, max: 0.2431, index: 15.

Row: 002, rank: 10, max: 0.2331, index: 1.

Row: 003, rank: 110, max: 0.2330, index: 10.

也就是說,場row用零填充,使這些數字有三位數字。該字段max也被填充以便它具有固定的長度。 rankindex都沒有填充。

[編輯此帖後添加]此外,在數據前面有幾行不相關的文本。不相關文本的行數是未知的。一條線的格式如上,當且僅當它低於線:DATA START BELOW

有沒有辦法使用命令

[A, count] = fscanf(fid,['what is a proper format?'],[?, numberOfRows]);

A = A';B = A(:,[i,j,k,l]);

這樣B=[1,6,0.2431,15; 2,10,0.2331,1; 3,110,0.2330,10;];讀取文件?

我知道的一種方法是[A, count] = fscanf(fid,['%s %d, %s %d, %s %f, %s %d.'],[AnInstantNumberRelatedToTheLengthOfALine, numberOfRows]);但是,當每個行附加新字段時,這種方法似乎缺乏靈活性。

回答

0

這裏有一種方法:

s = importdata('file.txt'); %// read file as cell array of strings; one line per string 
s = [s{:}]; %// concatenate into a single string 
ind = regexp(s, 'DATA START BELOW', 'end'); %// locate line that marks start of data 
s = s(ind+1:end); %// keep only data 
s = regexp(s, '-?\d+\.?\d*', 'match'); %// extract numbers as a cell array of strings 
s = str2double(s); %// convert to numbers 
s = reshape(s.', 4, []).'; %// reshape into four columns in row-mayor order 
+0

感謝您的答覆。我忘記提及在數據之前可能會有多行(行數不同)。 「Data Start Here」行下面的所有數據都是有效的。有什麼辦法來處理它?我嘗試了你的方法,但它顯示了「來自非單元格數組對象的單元格內容引用」。對於命令s = [s {:}];'。 – user3813057

+0

請修改問題中的示例以反映文件的確切格式 –

+0

請參閱編輯答案。我已經添加了兩行來處理這個問題 –

0

另一個答案:

fileID = fopen('mydata.txt'); 
C = textscan(fileID,'%s %f %s %f %s %f %s %f','delimiter',{',','Row:','max:','rank:','index:'}); 
fclose(fileID); 
C = C(2:2:8);