gpt4 book ai didi

arrays - 将矢量值加起来直到阈值,然后重新开始

转载 作者:太空宇宙 更新时间:2023-11-03 20:32:46 25 4
gpt4 key购买 nike

我有一个向量 a = [1 3 4 2 1 5 6 3 2]。现在我想用 acumsum 创建一个新的向量“b”,但是在达到阈值后,比方说 5,cumsum 应该重置并重新开始,直到再次达到阈值,因此新向量应如下所示:

b = [1 4 4 2 3 5 6 3 5]

有什么想法吗?

最佳答案

您可以构建一个稀疏矩阵,在与原始向量相乘时返回累积和。我没有将此解决方案与其他解决方案进行计时,但我强烈怀疑这将是大型 a 数组中最快的。

% Original data
a = [1 3 4 2 1 5 6 3 2];
% Threshold
th = 5;
% Cumulative sum corrected by threshold
b = cumsum(a)/th;
% Group indices to be summed by checking for equality,
% rounded down, between each cumsum value and its next value. We add one to
% prevent NaNs from occuring in the next step.
c = cumsum(floor(b) ~= floor([0,b(1:end-1)]))+1;
% Build the sparse matrix, remove all values that are in the upper
% triangle.
S = tril(sparse(c.'./c == 1));
% In case you use matlab 2016a or older:
% S = tril(sparse(bsxfun(@rdivide,c.',c) == 1));
% Matrix multiplication to create o.
o = S*a.';

关于arrays - 将矢量值加起来直到阈值,然后重新开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44436010/

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