题
我已经有了一些工作的代码,但是一个瓶颈,并且我坚持试图找出如何加速它。这是在一个循环,我可不图如何矢量化。
我已经有了一个2D阵列,vals,表示时间序列数据。行日期,列不同的系列。我想桶的数据按几个月来执行各种操作(总之,意思是,等等)。这是我目前代码:
allDts; %Dates/times for vals. Size is [size(vals, 1), 1]
vals;
[Y M] = datevec(allDts);
fomDates = unique(datenum(Y, M, 1)); %first of the month dates
[Y M] = datevec(fomDates);
nextFomDates = datenum(Y, M, DateUtil.monthLength(Y, M)+1);
newVals = nan(length(fomDates), size(vals, 2)); %preallocate for speed
for k = 1:length(fomDates);
这一线的瓶颈因为我把它叫做这么多的时间。(环)
idx = (allDts >= fomDates(k)) & (allDts < nextFomDates(k));
bucketed = vals(idx, :);
newVals(k, :) = nansum(bucketed);
end %for
任何想法?在此先感谢。
解决方案
这是一个困难的问题矢量.我可以建议的方式做到这一使用 CELLFUN, 但是我不能保证,它将以更快的问题(你会有时间自己的具体数据集使用的).作为讨论 这个这样的问题,矢量不 总是 工作速度比用于循环。它可以非常的问题-特定这是最好的选择。与这一声明,我建议两个方案为你要尝试:一CELLFUN版本和修改的用于环版本,可以跑得更快。
CELLFUN解决方案:
[Y,M] = datevec(allDts);
monthStart = datenum(Y,M,1); % Start date of each month
[monthStart,sortIndex] = sort(monthStart); % Sort the start dates
[uniqueStarts,uniqueIndex] = unique(monthStart); % Get unique start dates
valCell = mat2cell(vals(sortIndex,:),diff([0 uniqueIndex]));
newVals = cellfun(@nansum,valCell,'UniformOutput',false);
呼叫 MAT2CELL 团体的行为 沃尔斯 有相同的开始日期起进入细胞的一个电池阵列 valCell.变量 newVals 将是一个电池阵列的长度 numel(uniqueStarts), ,其中每个单元将包含结果的执行 nansum 在对应的单元 valCell.
对于环解决方案:
[Y,M] = datevec(allDts);
monthStart = datenum(Y,M,1); % Start date of each month
[monthStart,sortIndex] = sort(monthStart); % Sort the start dates
[uniqueStarts,uniqueIndex] = unique(monthStart); % Get unique start dates
vals = vals(sortIndex,:); % Sort the values according to start date
nMonths = numel(uniqueStarts);
uniqueIndex = [0 uniqueIndex];
newVals = nan(nMonths,size(vals,2)); % Preallocate
for iMonth = 1:nMonths,
index = (uniqueIndex(iMonth)+1):uniqueIndex(iMonth+1);
newVals(iMonth,:) = nansum(vals(index,:));
end
其他提示
如果你需要做的就是形成和或上一个矩阵,其中各行根据其他变量(日期)总结的行意味着然后用我的合并程序的功能。它是专门做的正是这种操作,减少基于一个指标系列的值的数据。 (实际上,集运也可以工作在n d的数据,并与宽容,但所有你需要做的是通过它的月和年信息。)
查找Matlab的中央文件交换集运
不隶属于 StackOverflow