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

标签 arrays matlab cumsum

我有一个向量 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/

相关文章:

matlab - 将所有变量转换为 gpuArrays 并不会加快计算速度

Python pandas cumsum()在达到最大值后重置

python - pandas 行中一系列零之前和之后的事件百分比

c - 在 C 中交换数组的元素

ios - 在 Swift 中转换语法以循环遍历数组数组

javascript - 当 "TypeError: array.splice is not a function"时如何解决 'var array = {}'?

matlab - 如何在Matlab中反转内联函数?

javascript - 使用 javascript 查找表行的最小值

python - 使用 python 评估滤波器 matlab 函数

python - 对 pandas 进行分组 cumsum,当 cumsum 为负数时将 cumsum 重置为 0