通常当某些事情从外部看起来很棘手时,从内部开始会更容易。我们如何从单个数组中获取最高日期?
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
请注意,像这样将不同的数据重新分配给相同的变量名称并不是特别好的做法 - 我今晚只是感觉异常懒惰,而且很难想出好的描述性名称;)