【问题标题】:MATLAB - Count Number of Entries in Each YearMATLAB - 计算每年的条目数
【发布时间】:2013-04-08 18:50:26
【问题描述】:

我有一个 .mat 文件,其中包含 2006-2100 年的数据。每年都有不同数量的线路。我需要数一下2006有多少行,2007有多少等等。

按列设置为:年、月、日、纬度、经度 我只想计算包含相同年份条目的行数,并返回一个包含该信息的数组的数组。

我认为 for 或 while 循环应该可以工作,但我不知道如何纠正它。

【问题讨论】:

    标签: matlab for-loop count while-loop sum


    【解决方案1】:

    如果我们假设您的数据在数字矩阵中,您可以这样做:

    num_lines2006 = sum(data(:,1)==2006);
    data2006 = data(data(:,1)==2006),:);
    

    如果要添加对应年份的行数列,这里有一个带循环的解决方案:

    for k=size(data,1):-1:1
        num_year(k,1) = sum(data(:,1)==data(k,1));
    end
    data = [data num_year];
    

    这是一个没有循环的解决方案:

    [unq_year,~,idx] = unique(data(:,1),'stable');
    num_year = grpstats(data(:,1),unq_year,@numel);
    data = [data num_year(idx)];
    

    【讨论】:

    • grpstats 需要统计工具箱。
    【解决方案2】:

    要计算数字条目,您可能需要使用histc

    years = unique(data(:,1);
    counts = histc(data(:,1),years);
    

    【讨论】:

      【解决方案3】:

      既然你只想计算行数,你可以写一些简单的东西,比如:

      years = unique(data(:, 1));
      counts = arrayfun(@(year) nnz(data(:, 1) == year), years);
      

      years 包含唯一的年份,numRows 包含它们被找到的次数。

      您还可以使用受 Jonas 回答启发的单线:

      [counts, years] = hist(data(:,1), unique(data(:,1))');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-21
        • 2014-06-02
        • 1970-01-01
        相关资源
        最近更新 更多