Matlab 根据条件语句对列的部分求和

Matlab 根据条件语句对列的部分求和,matlab,matrix,sum,conditional,Matlab,Matrix,Sum,Conditional,我在matlab中有一个矩阵,我想对一列的值求和,如果其他列使用条件语句进行检查,那么我想以一致的方式存储求和的值 布局输入表ListMax: year Month day hour precipitation 1998 1 1 1 5 1998 1 2 2 7 1998 1 3 3 0 .... ... ... ...

我在matlab中有一个矩阵,我想对一列的值求和,如果其他列使用条件语句进行检查,那么我想以一致的方式存储求和的值

布局输入表ListMax:

year    Month    day    hour    precipitation  
1998    1        1      1       5
1998    1        2      2       7
1998    1        3      3       0
....    ...     ...    ...      ...
布局输出结果矩阵:

year    jan    feb   mar    
1998    100    120   140
1999    90     110   130
...    ...     ...   ...
我正在对行进行排序,检查条件语句并将值保存到输出中

我有以下想法,但它不起作用:

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

我可以看出这可能不是最直接的方法,但目前这是我能想到的方法,现在我只需要让它工作到底。如果能朝着正确的方向推进,我们将不胜感激:

这个未经测试的产品怎么样:

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
您只需将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);