gpt4 book ai didi

matlab - 分桶算法

转载 作者:行者123 更新时间:2023-12-02 02:37:25 25 4
gpt4 key购买 nike

我有一些代码可以工作,但有点瓶颈,我一直在想办法加快它的速度。它处于循环中,我不知道如何对其进行矢量化。

我有一个二维数组 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 的方法,但我不能保证它会更快地解决您的问题(您必须自己对正在使用的特定数据集进行计时)。正如在 this other SO question 中讨论的那样,矢量化并不总是比 for 循环工作得更快。它可以是非常特定于问题的,这是最好的选择。有了这个免责声明,我会建议您尝试两种解决方案:CELLFUN 版本和可以运行得更快的 for-loop 版本的修改版本。

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将具有相同开始日期的 vals 行分组到元胞数组 valCell 的元胞中。变量 newVals 将是一个长度为 numel(uniqueStarts) 的元胞数组,其中每个元胞将包含对相应元胞执行 nansum 的结果valCell

FOR 循环解决方案:

[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

关于matlab - 分桶算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/863113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com