【问题标题】:How to convert specially formatted data from a text file to a matrix in MATLAB如何在 MATLAB 中将特殊格式的数据从文本文件转换为矩阵
【发布时间】:2013-11-19 10:32:42
【问题描述】:

我的文件如下 trial.txt

ReducedSize:    True         
Ref_Signal: Force        

1        0,0000000000e+000  -3,14703e-003    0,00000e+000
2            1,0000000000e+000   2,27451e-001    4,66456e-002
123      6,3990000000e+003   3,76442e+001   -6,59653e+000
643          6,4000000000e+003   3,76920e+001   -6,61744e+000
Tagin:           
Ovead:      False    
AveNumber: []        1,00000e+001

我想删除所有以文本开头或没有任何内容的行,然后将所有其余的数字数据放入一个 4 列的矩阵中,我所做的如下。

 fid = fopen('trial.txt', 'r') ;               % Open source file.
 fgetl(fid) ;                                  % Read/discard line.
 fgetl(fid) ;                                  % Read/discard line.
 buffer = fread(fid, Inf) ;                    % Read rest of the file.
 fclose(fid)                                   % first two lines DELETED

 fid = fopen('myFile_truncated.txt', 'w')  ;   % Open destination file.
 fwrite(fid, buffer) ;                         % Save to file.
 fclose(fid) ;

 Data = fileread('myFile_truncated.txt');
 Data = strrep(Data, ',', '.');
 FID = fopen('myFile_truncated1.txt', 'w');
 fwrite(FID, Data, 'char');
 fclose(FID);                                   % changed comma to points for data manipulation

dlmread('myFile_truncated1.txt')                % convert the data to MARTRIX

它工作正常,但是最后 3 行中的文本不会让它发生。谁能建议如何删除第一行和最后一行?还有如何删除不包含文本的行,以便绘制图形?

我确实认为有一种更聪明的方式来做这些事情。

【问题讨论】:

    标签: matlab matrix text editing


    【解决方案1】:

    这就是我要做的事情

    s = fileread('trial.txt'); % read file into string
    s = regexprep(s,',','\.'); % replace any comma with period
    s = regexprep(s,' +',' '); % replace any group of spaces with a single space 
    M = textscan(s,'%f %f %f %f',4,'HeaderLines',3); % read the numbers
    M = [M{:}]; % concatenate all cell elements into a matrix
    

    【讨论】:

    • 首先没有工作,其次页脚行呢?
    • ???使用 ==> textscan 时出错 格式错误的格式字符串。 ==> 在 390 M 处循环出错 = textscan(s,'%d %g %g %g',4,'HeaderLines',3);
    • 重新加载此网页并将代码复制粘贴到您的 MATLAB 控制台。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多