【问题标题】:Add values in array and compare with threshold within loop in Matlab在数组中添加值并与Matlab中循环内的阈值进行比较
【发布时间】:2017-09-02 10:50:00
【问题描述】:

我一直试图弄清楚这一点。我有一个数组:

a = [ 1 1 1 2 1 1 1 3 2 1 1 2 1 1 1]

我想add the values in the array so that it equal to 10。一旦添加的值达到 10,我希望数组再次开始添加值,直到达到 10。我在这里面临两个问题,

1) 我怎样才能添加数组,以便 sum = 10 每次。请注意,在数组中,有3。如果我在3 之前添加所有值,我会得到8,我只需要来自32。我需要确保将余数(即 1)添加到下一个数组中以获得总和 10

2) 一旦循环到达10,我如何打破循环并要求它继续求和到下一个值以获得另一个10

我创建了一个循环,但它只适用于数组的第一部分。我不知道如何让它继续。代码如下:

a = [ 1 1 1 2 1 1 1 3 2 1 1 2 1 1 1]; 
c = 0; 

for i = 1:length(a) 
   while c < 10
      c = c + a(i);
   break
   end
end

请帮忙。谢谢

【问题讨论】:

  • 给定a 的输出是什么?
  • @SardarUsama 我不清楚你的问题。我将a 初始化为具有指定值的数组,就像在代码中一样,所以如果我在 Matlab 中运行a,它会给我那些指定的值。
  • 这是我面临的问题之一,我需要添加数组值,这样一旦数组值的总和等于10,我就会确定最后一个的索引对总和有贡献的数组。所以在数组a 中,我有a[1] until a[8] 的总和等于10。但是,正如问题的第(1)点所述,a[8] 中会有余数,即1。我想将余数添加到a[9] 中的下一个值,以获得另一个等于10 的总和。我不确定我的解释是否清楚,但我希望我能从中找到一些答案。
  • @SardarUsama 预期的输出是[8,15]

标签: arrays matlab for-loop while-loop


【解决方案1】:

这可以使用cumsummoddifffind 来完成,如下所示:

temp = cumsum(a);
required = find([0 diff(mod(temp,10))] <0)

cumsum 返回累积和,然后使用mod 重新调整。 diff 确定总和大于或等于 10 的位置,最后find 确定这些索引。

编辑: 如果a 没有负面元素,则上述解决方案有效。如果a 可以有否定元素,那么:

temp1=cumsum(a);              %Commulative Sum
temp2=[0 diff(mod(temp1,10))];%Indexes where sum >=10 (indicated by negative values)
temp2(temp1<0)=0;             %Removing false indexes which may come if `a` has -ve values
required = find(temp2 <0)     %Required indexes

【讨论】:

  • 谢谢@SardarUsama
【解决方案2】:

这应该做你正在尝试的。它显示每次总和等于 10 的索引。用你的测试用例检查这个。 rem 存储每次迭代中的残差和,并在下一次迭代中结转。其余代码与您所做的类似。

a = [ 1 1 1 2 1 1 1 3 2 1 1 2 1 1 1]; 
c = 0; 
rem = 0;
i = 1;
length(a);
while(i <= length(a))
   c = rem; 
   while (c < 10 && i <= length(a))
      c = c + a(i);
      i = i + 1;
      if(c >= 10)
        rem = c - 10;
        break
      end
   end
   if(c >= 10)
      disp(i-1)
end

【讨论】:

    【解决方案3】:

    使用cumsum 而不是while 循环:

    a = [ 1 1 1 2 1 1 1 3 2 1 1 2 1 1 1];
    a_ = a;
    endidxlist = false(size(a));
    startidxlist = false(size(a));
    startidxlist(1) = true;
    while any(a_) && (sum(a_) >= 10)
        b = cumsum(a_);
        idx = find(b >= 10,1);
        endidxlist(idx) = true;
        % move residual to the next sequence
        a_(idx) = b(idx) - 10;
        if a_(idx) > 0
            startidxlist(idx) = idx;
        elseif (idx+1) <= numel(a)
            startidxlist(idx+1) = true;
        end
        a_(1:idx-1) = 0;
    end
    if (idx+1) <= numel(a)
        startidxlist(idx+1) = false;
    end
    

    endidxlist 为您提供每个序列的结束索引,startidxlist 为您提供开始索引

    【讨论】:

    • 好点,我编辑了我的答案以使用预分配的二进制数组。
    猜你喜欢
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    相关资源
    最近更新 更多