2010-02-11 93 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