簡體   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