2010-02-11 42 views
0

我有一個文本文件,但不幸的是它格式不好,但我想讀取文本文件的內容到一個矩陣,但我不知道該怎麼做。閱讀文本文件,以不同格式的MATLAB

當試圖使用fscanf,textscan,textread和其餘的它只是複製一切到一個單元格,但我不想這樣。

這個內容是怎麼樣的:所以我想只讀取小數而不是絕對數字。有人能幫我嗎。

1 : 13.27 ; 3 : 20.68 ; 6 : 8.271 ; 7 : 3.308 ; 8 : 8.328 ; 
9 : 6.655 ; 10 : 16.58 ; 11 : 9.925 ; 12 : 12.41 ; 13 : 4.135 ; 
14 : 9.925 ; 15 : 11.58 ; 16 : 10.87 ; 17 : 1.654 ; 18 : 4.962 ; 
19 : 6.655 ; 22 : 10.98 ; 23 : 24.25 ; 24 : 47.33 ; 25 : 11.6 ; 
26 : 9.925 ; 27 : 5.809 ; 28 : 5.001 ; 29 : 6.617 ; 30 : 7.577 ; 
31 : 9.155 ; 32 : 7.444 ; 33 : 28.58 ; 34 : 9.155 ; 35 : 35.83 ; 
+0

我可以幫你,但我不知道你想要什麼。你能給出給定輸入的期望輸出嗎?或者,您可以爲較小的輸入提供所需的輸出嗎? – forefinger 2010-02-11 00:43:50

+0

另外,你在哪個環境中運行?你有權訪問Perl,Python等?我知道您使用的是MATLAB,但使用更合適的工具將您的數據轉換爲MATLAB的ascii矩陣格式,然後以通常的方式進行加載可能會更簡單。 – forefinger 2010-02-11 00:48:56

回答

1

概念:

採取的字符串。

更改:和;與空格和\ n(返回);

將該字符串賦值給一個變量,該變量應該成爲一個矩陣。

了雙循環改變每個elemnt的值與

var(i,j)=floor(var(i,j)) - var(i,j); 

給你(如果我沒誤會你了)。

2

我認爲冒號(:)分隔行中的值,分號(;)分隔行。在這個假設下功能應該閱讀你的數據轉換成MATLAB矩陣

function dat = readData(filename) 
% FUNCTION dat = readData(filename) 
% Reads data from a nonstandard formatted file, filename 
% INPUTS: 
% filename: Full path to data file with the following format 
%      1 : 2; 3 : 4 
%    where the : separates values in a row and ; separates rows 

% open the file for reading 
fid = fopen(filename); 

ii=0; % row index 

while ~feof(fid) % loop until we find the end of the file 
    str = fgetl(fid); % get a line of text 

    while 1 
     % split the string into its component parts 
     % assume that values are split with colon ":" and 
     % rows are identified with a 
     % semicolon ";". 
     % 
     % split at the first row using strtok 
     [rowStr rem]=strtok(str,';'); 

     % split rowStr using colon 
     [str1,str2]=strtok(rowStr,':'); 

     % get rid of the colon in str2 
     str2 = strrep(str2,':',' '); 

     str1 =strtrim(str1); 
     str2 =strtrim(str2); 

     % store data if we found any 
     if ~isempty(str1)&& ~ isempty(str2) 
      ii=ii+1; % increment row index 
      dat(ii,:) = [str2double(str1) str2double(str2)]; 
     end 

     if isempty(rem), break; end 
     str = rem(2:end); 
    end 
end 
fclose(fid); 

可以比使用功能全面,樓層,小區提取「十進制值」。

4

只需使用textscan,而忽略你不需要,喜歡的數字和事:給你一個非常簡單的解決辦法:

fid = fopen('test.txt', 'rt'); 
data = textscan(fid, '%*u %*1s %f', 'Delimiter', ';'); 
fclose(fid); 

變化的test.txt到您的文件名。數據是一個包含雙打的單元格。

>> data{:} 

ans = 

    13.2700 
    20.6800 
    8.2710 
    3.3080 
    8.3280 
    6.6550 
    16.5800 
    9.9250 
    12.4100 
    4.1350 
    9.9250 
    11.5800 
    10.8700 
    1.6540 
    4.9620 
    6.6550 
    10.9800 
    24.2500 
    47.3300 
    11.6000 
    9.9250 
    5.8090 
    5.0010 
    6.6170 
    7.5770 
    9.1550 
    7.4440 
    28.5800 
    9.1550 
    35.8300