在列元素MATLAB中插入空格/制表符以分隔字段

时间:2016-05-27 23:58:59

标签: matlab matrix time-series

我有一个矩阵如下:

615319419701102123000000 000000 000000 000000 000000 000000 000000 000003 000000 000000 000000 000000 000000 000000 000000 000000 000000 000000 000000 000000 000000 000000 000000 000000

矩阵有24列。在第1列中,7位数表示(即6153194)统计ID,接下来的4位数年份(1970年),接下来的2位数月份(11表示11月份),接下来的2位数表示该月份的日期(例如, 第1列02表示第2天),然后123表示其降水率和最后6位数的时间序列(即000000是降雨量)。最后23列表示每小时降雨量数据,单位为mm。

我想将第1列的字段分为电台ID,年,月,日和价值,以便输入程序,如下所示:

6153194 1970 11 02 123 000000 000000 000000 000000 000000 000000 000000 000003 000000 000000 000000 000000 000000 000000 000000 000000 000000 000000 000000 000000 000000 000000 000000 000000

最后是一个时间序列:

6153194 1970    11  2   123 0
6153194 1970    11  2   123 0
6153194 1970    11  2   123 0
..................
.................
6153194 1970    11  2   123 0
6153194 1970    11  2   123 0

我主要关心的是如何使用第一列中的制表符/空格分隔字段,以及如何构建时间序列?有关此

的任何帮助/建议

1 个答案:

答案 0 :(得分:0)

下面的代码应该产生我相信你想要产生的输出。但是,如果我完全理解你的问题,我并不完全确定。如果您需要不同格式的数据,请告诉我,我会修改代码。

运行代码后,charMatrix将包含数据作为字符数组,第一列分隔,如问题中的示例所示。 numMat是一个数组,其中包含与charMatrix对应的数字数据。

%% Subdivision of the first column.

% Read the data.
fid = fopen('file.txt');
charCell = textscan(fid, '%s', 'delimiter', '\n');
charCell = charCell{1};

% Split by whitespace.
charCell = cellfun(@strsplit, charCell, 'UniformOutput', false);

% Split the first column.
charCell = cellfun( ...
    @(charMatrixRow) { ...
    charMatrixRow{1}(1 : 7) ...
    charMatrixRow{1}(8 : 11) ...
    charMatrixRow{1}(12 : 13) ...
    charMatrixRow{1}(14 : 15) ...
    charMatrixRow{1}(16 : 18) ...
    charMatrixRow{2 : end} ...
    }, ...
    charCell, ...
    'UniformOutput', false ...
    );

% Join individual columns with a whitespace delimiter.
charMatrix = cellfun( ...
    @strjoin, charCell, 'UniformOutput', false ...
    );

% If you would like to get the values in the form of a character array:
charMatrix  = cell2mat(charMatrix);

%% Numeric representation of the columns.
% If you would like to get the individual columns in the form of numeric
% arrays, use the code below.

charCell = vertcat(charCell{:});

numMat = cell2mat(cellfun(@str2num, charCell, 'UniformOutput', false));