我在matlab中有一个矩阵,如果其他列用条件语句检查,我想要对列的值求和,然后我想以连贯的方式存储求和的值。
布局输入表ListMax:
year Month day hour precipitation
1998 1 1 1 5
1998 1 2 2 7
1998 1 3 3 0
.... ... ... ... ...
布局输出result_matrix:
year jan feb mar
1998 100 120 140
1999 90 110 130
... ... ... ...
我正在使用itirating对行的组合,检查条件语句并将值保存在输出中。
我记得以下内容,但它不起作用:
result_matrix = zeros(15,12); %empty matrix 15 years, 12 months
year_number = 1998;
counting_years = 1;
counting_months = 1;
for (ii = 1: length(ListMax));
if ListMax(:,1) == year_number && ListMax(:,2) == counting_months;
result_matrix(counting_years, counting_months) = (sum(Listmax(:,5));
else % update month itirators
if counting_months < 12
counting_months = counting_months + 1;
else % end of year, set month count to 1
counting_months = 1;
end
year_number = year_number +1;
counting_years = counting_years + 1;
end
end
我可以看到这可能不是最简单的方法,但目前这是我能想到的方法,现在我只需要让它工作即可。任何正确方向的推动都将非常感激:)
答案 0 :(得分:1)
您可以简单地将accumarray
与两列子索引一起使用。
year Month day hour precipitation
1998 1 1 1 5
1998 1 2 2 7
1998 1 3 3 0
.... ... ... ... ...
例如,如果要根据年份和月份对降水总量求和,可以使用矩阵的第一列作为索引,最后一列作为降水值。
sub = 1998 1 %Jan.1998
1998 1 %Jan.1998
1998 2 %Feb.1998
...
sub(:,1) = sub(:,1) - (min(sub(:,1))-1); %so the index for the year start at 1 and not 1998.
val = 6 %millimeter of precipitation on Jan.1998 day xxx
4 %millimeter of precipitation on Jan.1998 day xxx
7 %millimeter of precipitation on Feb.1998 day xxx
....
现在使用accumarray
:
result = accumarray(sub,val,[],@sum);
答案 1 :(得分:0)
这个(未经测试)如何:
year_start = 1998;
year_end = 2016;
result_matrix = zeros(year_end-year_start+1,12);
for year = year_start:year_end
for month = 1:12
rows = (ListMax(:,1)==year) & (ListMax(:,2)==month);
result_matrix(year-year_start+1,month) = sum(ListMax(find(rows),5));
end
end