本文介绍了读取文本文件,matlab的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读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应该是什么)%这行是
问题%

fclose fid);

任何帮助

解决方案

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

  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
>&g t; C {2,end}
ans =
1 3 4 23


I am reading a text file 'mytext.text' in matlab. Data file looks like:

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

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

....

I don't know the length of Col5. How can I read it in matlab?

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

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

fclose(fid);

Any help.

解决方案

One possibility is to read the last column as string, then convert it to numbers afterward.

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)]

The resulting cell-array:

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

with:

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

这篇关于读取文本文件,matlab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 07:46