将文本文件导入Matlab,未维护维度

时间:2015-06-25 22:23:23

标签: matlab matrix import dimension

我正在尝试将文本文件作为矩阵上传到matlab,然后根据用户输入进行处理,以便选择所选数据。

这些是数据的前几行。

The United States of America, Deaths (1x1)     Last modified: 16-Nov-2012, MPv5 (May07)

Year     Age        Female             Male            Total
1933      0          52615.77         68438.11        121053.88
1933      1           8917.13         10329.16         19246.29
1933      2           4336.92          5140.05          9476.97
1933      3           3161.59          3759.88          6921.47
1933      4           2493.84          2932.59          5426.43
1933      5           2139.87          2537.53          4677.40
1933      6           1939.70          2337.76          4277.46
1933      7           1760.47          2163.90          3924.37
1933      8           1602.20          2015.97          3618.17
1933      9           1464.88          1893.96          3358.84

这里有大部分数据:https://www.dropbox.com/s/b4njypwmrxwxzl7/USA.Deaths_1x1.txt?dl=0

我面临的问题是,每次我使用T=readable()读取数据时,T的维度为m x 1表,而不是m x 5表。

我还尝试将txt文件更改为csv文件,但数据包含非数字条目。

我该怎么做才能解决这个问题?

感谢。

1 个答案:

答案 0 :(得分:0)

对于您的数据格式,大多数直接导入功能(importdatadlmread等等)都将失败。

textscan有一些参数可以让你导入整个文件而不会破坏第一个不规则的行,但是一些错误的行将包含NaN

%// Define special values which can be encoutered
specialValues = {'110+','other_special_values'} ;
formatSpec = '%n%n%f%f%f' ;

%// Read the file, treating special values 
fileID = fopen('USA.Deaths_1x1.txt');
C = textscan(fileID, formatSpec, ...
    'delimiter'     , ' ', ...
    'headerlines'   ,3, ...
    'treatAsEmpty'  , specialValues, ...
    'MultipleDelimsAsOne',1 );

fclose(fileID);

%// Convert cell array to matrix
data = cell2mat(C) ;

如果你确实需要有缺陷的行数据,那么你必须编写一个带有低级函数fscanf的更自定义的解析器,并考虑你可能遇到的每个边缘情况(非常规行)。 / p>

相关问题