繁体   English   中英

列的总和取决于条件语句Matlab

[英]Sum parts of column depending on conditional statement Matlab

我在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
...    ...     ...   ...

我正在努力进行行初始化,检查条件语句以及将值保存在输出中的组合。

我有以下几点注意事项,但不起作用:

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

我可以看到这可能不是最直接的方法,但是目前我能想到的这种方法,现在只需要使它正常工作即可。 任何朝着正确方向的推动将不胜感激:)

您可以简单地将accumarray与两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);

怎么样(未试用):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM