0

我有一个包含两列的 .txt 文件:第一列保存日期,第二列保存该日期的降水量 (ppt) 的浮点值。我想通读降水列并总结每次风暴的降水量。风暴被零降水周期分隔。因此,我基本上想告诉 Matlab 读取 ppt 列,将值相加直到它读取到 0,然后将和放入向量的单元格中,然后继续阅读并重复。我知道我需要一个带有条件语句的循环。根据我对 Matlab 的有限了解,我认为成功的代码可能类似于以下内容:

fid = fopen(12hr_ppt.txt');
C = textscan(fid);
l = length(fid);
? = 0;
for i=1:l;
    if fid(i)>0;
        ?=fid(i)+?;
    else
        ?=0;
    endif
    fprintf(?);
end

所以我基本上想要?是一个包含总降水量的向量。拥有与事件相对应的日期也非常好,但现在我只想解决这个问题。任何帮助是极大的赞赏!

4

1 回答 1

0

您可以使用以下内容:

clear;
close;
clc;

date_ppt = importdata('testcase.txt');
num_rows = size(date_ppt.data,1);
end_storm = find(date_ppt.data == 0);
if(end_storm(1) == 1)
    end_storm = end_storm(2:end);
end
if(end_storm(end) ~= num_rows)
    end_storm = [end_storm;num_rows];
end
begin_storm = [1;(end_storm(1:(end-1)) + 1)];

accumulated_ppt = zeros(size(begin_storm));

for i = 1:numel(accumulated_ppt)
    accumulated_ppt(i) = sum(date_ppt.data(begin_storm(i):end_storm(i)));
end

accumulated_ppt

在这里,我的“testcase.txt”包含以下内容:

Date    PPT
01/01/13    0.276
02/01/13    0.6797
03/01/13    0.6551
04/01/13    0.1626
05/01/13    0
06/01/13    0.4984
07/01/13    0.9597
08/01/13    0.3404
09/01/13    0.5853
10/01/13    0.2238
11/01/13    0.7513
12/01/13    0.2551
13/01/13    0.506
14/01/13    0.6991
15/01/13    0.8909
16/01/13    0.9593
17/01/13    0.5472
18/01/13    0
19/01/13    0.1493
20/01/13    0.2575
21/01/13    0.8407
22/01/13    0.2543
23/01/13    0.8143
24/01/13    0.2435
25/01/13    0.9293
26/01/13    0.35
27/01/13    0.1966
28/01/13    0.2511
29/01/13    0.616
30/01/13    0.4733
31/01/13    0.3517
01/02/13    0.8308
02/02/13    0.5853
03/02/13    0.5497
04/02/13    0.9172
05/02/13    0.2858
06/02/13    0.7572
07/02/13    0.7537
08/02/13    0.3804
09/02/13    0.5678
10/02/13    0.0759
11/02/13    0
12/02/13    0.5308
13/02/13    0.7792
14/02/13    0.934
15/02/13    0.1299
16/02/13    0.5688
17/02/13    0.4694
18/02/13    0.0119
19/02/13    0.3371

得到的输出是:

accumulated_ppt =

    1.7734
    7.2165
   11.4314
    3.7611

此外,“日期”列值存储在date_ppt.textdata(:,1). 例如,如果你想要对应的日期end_storm,你可以简单地使用`date_ppt.textdata(end_storm,1)':

>> date_ppt.textdata(end_storm,1)

ans = 

    '04/01/13'
    '17/01/13'
    '10/02/13'
    '18/02/13'
于 2013-05-02T06:05:27.140 回答