2012-07-12 14 views
1

該文件是一個輸出文件,其第一行是一個標題,後面跟着帶有數據的n行。第一組數據後面跟着更多類似的具有不同數值的數據組。如何閱讀這個文件(重複模式)列明智的Matlab?

我想讀此文件中的第2和第3列的數據,即direction 1direction 2等。目前我使用的是函數內的以下幾行代碼來讀取數據的所有集合,如下圖所示:

fid = fopen(output_file); % open the output file 

dotOUT_fileContents = textscan(fid,'%s','Delimiter','\n'); % read it as string ('%s') into one big array, row by row 
dotOUT_fileContents = dotOUT_fileContents{1}; 
fclose(fid); %# close the file 

%# find rows containing 'SV' 
data_starts = strmatch('SV',... 
    dotOUT_fileContents); % data_starts contains the line numbers wherever 'str2match' is found 
nDataRows=data_starts(2)-data_starts(1)-1; 
ndata = length(data_starts); % total no. of data values will be equal to the corresponding no. of 'str2match' read from the .out file 

%# loop through the file and read the numeric data 
for w = 1:ndata 

    %# read lines containing numbers 
    tmp_str = dotOUT_fileContents(data_starts(w)+1:data_starts(w)+nDataRows); 

    %# convert strings to numbers 
    y = cell2mat(cellfun(@(z) sscanf(z,'%f'),tmp_str,'UniformOutput',false)); % store the content of the string which contains data in form of a character 
    data_matrix_column_wise(:,w) = y; % convert the part of the character containing data into number 

    %# assign output in terms of lag and variogram values 
    lag_column_wise(:,w)=data_matrix_column_wise(2:6:nLag*6-4,w); 
    vgs_column_wise(:,w)=data_matrix_column_wise(3:6:nLag*6-3,w); 
end 

如果我沒有在上面的輸出文件中顯示星星,此功能運行良好。但是,上面顯示的輸出文件之一包含星號,上面的代碼在這種情況下失敗。應該怎樣處理數據中的星號以便我能夠正確讀取第2列和第3列?

回答

3

的問題是你的這部分代碼:

sscanf(z,'%f') 

你強迫匹配浮點數,並在遇到星失敗。你可能會更好的東西代替,像

textscan(z, '%f %f %f %s %f %f', 'Delimiter', '\t') 

並刪除cell2mat並適當地修改以下行來測試字符串的存在。

或者,這取決於那些星星的含義,你可以用一個零代替某些有意義的東西,而你當前的代碼可以正常工作。

+0

不客氣 - 祝你好運! – Ansari 2012-07-13 19:47:48

1

閱讀所有的列字符串:

C = textscan(fid, '%s%s%s%s%s%s'); 

這給你一個C是一個單元陣列有6列。您可以訪問C的元素: 對於列n和行m,C {1,n} {m}。 然後在for循環中,你可以從48減去值,讓你的數字是這樣

for n=1:6 
    for m=1:M 
     A(m,n) = C{1,n}{m}-48; 
    end 
end 

什麼,你需要將存儲在矩陣A.當然,你可以比較C {1,N} {M}中與這8星級,並決定你想要做什麼。

+0

感謝您的回答! – Pupil 2012-07-13 18:29:09