【问题标题】:Count the number of times something showed up in the top 36 rows计算前 36 行中出现的次数
【发布时间】:2014-03-31 20:06:25
【问题描述】:

我有一个大小为 1x7 的单元格,其中每个单元格是 365x5xN,其中每个 N 是不同的位置(siteID)。它已经根据第 5 列(列是 Lat、Lon、siteID、date 和 data)进行了排序。 (数据可以在这里找到:https://www.dropbox.com/sh/li3hh1nvt11vok5/4YGfwStQlo。有问题的变量是 PM25)

我想遍历整个 1x7 单元格,只查看前 36 行(基本上是前 10 个百分位数),计算每个日期出现的次数。换句话说,我想知道数据值在哪一天落入前 10 个百分位。

有人知道我该怎么做吗?我不知道如何解决这个问题->计算所有这些单元格并为一年中的每一天吐出一个数量

【问题讨论】:

    标签: matlab count


    【解决方案1】:

    假设你有一个排序的元胞数组,你可以使用这个 -

    %%// Get all the dates for all the rows in sorted cell array
    all_dates = [];
    for k1=1:size(sorted_cell,2)
        all_dates = [all_dates reshape(cell2mat(sorted_cell{1,k1}(:,4,:)),1,[])];
    end
    all_unique_dates = unique(all_dates);
    all_out = [num2cell(all_unique_dates)' num2cell(zeros(numel(all_unique_dates),1))];%%//'
    
    %%// Get all the dates for the first 36 rows in sorted cell array
    dates = [];
    for k1=1:size(sorted_cell,2)
        dates = [dates reshape(cell2mat(sorted_cell{1,k1}(1:36,4,:)),1,[])];
    end
    
    %%// Get unique dates and their counts
    unique_dates = unique(dates);
    count = histc(dates, unique_dates);
    
    %%// As output create a cell array with the first column as dates 
    %%// and the second column as the counts
    out = [num2cell(unique_dates)' num2cell(count)']
    
    %%// Get all the dates and the corresponding counts. 
    %%// Thus many would still have counts as zeros.
    all_out(ismember(all_unique_dates,unique_dates),:)=out;
    

    【讨论】:

    • 谢谢。这很好用。但我有个问题。我得到258天。那是因为省略了任何为零的日子吗?
    • 是否可以保留所有天数,因为我将沿 x 轴用天数绘制它们,并且有间隙会使这变得更加复杂。
    • @shizishan 是的,很可能是因为我们只选择了前 36 行。那么,您仍然想从前 36 行中进行选择,但获取所有日期,仅用于绘图?
    • 谢谢!那效果很好。我还不熟悉编码,所以你们的 cmets 帮助我展示了一些思考问题的方法。
    【解决方案2】:

    通常当某些事情从外部看起来很棘手时,从内部开始会更容易。我们如何从单个数组中获取最高日期?

    dates = unique(array(1:35,4));
    

    现在,如何为每个单元格执行此操作?循环总是很简单,但这是一个非常简单的函数,所以让我们使用单线:

    datecell = cellfun(@(x) unique(x(1:35,4)), cellarray, 'UniformOutput', false);
    

    现在每个单元格都有我们想要的日期。如果不需要将它们分开,让我们将它们全部放在一个大数组中:

    dates = cell2mat(datecell);
    dates = unique(dates);  % in case there are any duplicates
    

    如果你也想真正计算每个日期(有点不清楚),对于匿名函数来说可能有点过于复杂,所以我们可以编写自己的函数来传递给cellfun,或者干脆把它粘在一个循环中:

    dates = {};
    counts = {};
    for ii = 1:length(cellarray)
        [dates{ii}, ~, idx] = unique(cellarray{ii}(1:35,4));
        counts{ii} = accumarray(idx, 1);
    end
    

    现在,这些元胞数组可能包含重复项,因此我们必须在必要时以类似方式合并计数:

    dates = cell2mat(dates);
    counts = cell2mat(counts);
    [dates, ~, idx] = unique(dates);
    counts = accumarray(idx, counts);  % add the counts of duplicated dates together
    

    请注意,像这样将不同的数据重新分配给相同的变量名称并不是特别好的做法 - 我今晚只是感觉异常懒惰,而且很难想出好的描述性名称;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-09
      相关资源
      最近更新 更多