【问题标题】:Matlab: Daily 3d array to monthly- dealing with alternate days in a month and leap years - How to do it?Matlab:每日 3d 数组到每月 - 处理一个月中的隔日和闰年 - 怎么做?
【发布时间】:2019-10-26 08:58:48
【问题描述】:

在 matlab 中,我有一个 720x360x365 矩阵(我们称它为 A),表示一年的每日降水量。 365 代表一年中的天数。我需要编写代码将这些每日数据转换为每月总和。如果我从一月开始,我需要计算前 31 天的平均值 (A,3),然后是二月的平均值 (A,3),接下来的 28 天或 29 天。因为日子在 31 和 30 之间交替(以及 2 月的 28 或 29),我不知道如何编写代码来执行此操作。 请帮助我,我不知道该怎么做。 谢谢

【问题讨论】:

    标签: arrays matlab matrix


    【解决方案1】:

    您可以使用mat2cell 每月将数据划分为单元格。首先制作一个带有每月天数的向量(不考虑闰年),然后用它来划分数据。然后您可以在每个单元格(即月份)上使用cellfun 来获取您每月定义的任何指标:

    data =  rand(720, 360, 365);
    days_per_month = [31 28 31 30 31 30 31 31 30 31 30 31];
    
    % divide months in cells
    data_cell = mat2cell(data, size(data,1), size(data,2), days_per_month);
    mean_cell = cellfun(@(A) mean(A,3), data_cell, 'UniformOutput', false)
    

    要在循环中使用它并考虑闰年,您可以使用函数leapyear(year)

    days_per_month = [31 28 31 30 31 30 31 31 30 31 30 31];
    years = 1984:2015
    for k = 1:numel(years)
        if leapyear(years(k))
            days_per_month(2) = 29;
        else
            days_per_month(2) = 28;
        end
    
        % rest of what you want to do
    
    end
    

    【讨论】:

    • 实际上我需要使用循环应用您的上述代码 34 年,从 1984 年到 2015 年。所以如果你也能帮助我处理闰年。
    猜你喜欢
    • 1970-01-01
    • 2020-08-19
    • 2013-01-16
    • 2013-06-18
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多