【问题标题】:Reading text file, matlab读取文本文件,matlab
【发布时间】:2011-09-23 13:02:35
【问题描述】:

我正在 matlab 中读取文本文件“mytext.text”。数据文件如下:

1   -4436.6910  415.1843    -3019.7497  1,3,4,5,21,23

2   -4366.4541  1353.9975   -3085.1166  1,3,4,23

....

我不知道 Col5 的长度。如何在 matlab 中读取?

fid=fopen( 'mytext.text','r');

Grdata = textscan(fid, '%d %f %f  %f  (Col 5 what should be)% This line is 
problem%  

fclose(fid); 

任何帮助。

【问题讨论】:

  • 逗号是文件格式的组成部分吗?如果逗号可以替换为空格(例如前 3 个数字),您也许可以使用dlmread。读取的结果数据将具有可以告诉您缺少哪些列等的维度。这是您要查找的内容吗?

标签: matlab file-io


【解决方案1】:

一种可能性是将最后一列读取为字符串,然后将其转换为数字。

fid = fopen('file.dat','r');
C = textscan(fid, '%f %f %f %f %s', ...
    'Delimiter',' ', 'MultipleDelimsAsOne',true, 'CollectOutput',true);
fclose(fid);

C = [num2cell(C{1}) cellfun(@str2num, C{2}, 'UniformOutput',false)]

生成的元胞数组:

C = 
    [1]    [-4436.7]    [415.18]    [-3019.7]    [1x6 double]
    [2]    [-4366.5]    [  1354]    [-3085.1]    [1x4 double]

与:

>> C{1,end}
ans =
     1     3     4     5    21    23
>> C{2,end}
ans =
     1     3     4    23

【讨论】:

    【解决方案2】:

    读取一行代码

    % Read at most 4 elements
    data1234 = fscanf (fid, '%d %f %f %f', 4);
    % Read as many elements as possible, stop when no ',' is found
    data5 = fscanf (fid, '%d,');
    

    继续阅读行,直到到达文件末尾(在此之前保存每一行的数据)。因此,您需要一些循环来继续执行此操作,直到文件结束。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-07
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      相关资源
      最近更新 更多