2017-04-07 45 views
0

我被困在试图弄清楚这一点。我有一个数组:在Matlab中添加数组中的值并与循环内的阈值比较

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,我只需要23。我需要确保剩余部分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 

请帮忙。谢谢

+0

给定'a'的输出是什么? –

+0

@SardarUsama我不清楚你的问题。我将'a'初始化为具有指定值的数组,如代码中所示,所以如果我在Matlab中运行'a',它会给我那些指定的值。 – loss

+0

这是我面临的问题之一,我需要添加添加数组值,以便一旦数组值的总和等于'10',我将确定最后一个数组的总和索引。所以在数组'a'中,我有'a [1],直到[8]'有助于总和等于'10'。然而,正如问题的第(1)点所述,'a [8]'中有余数,即'1'。我想把余数加到'a [9]'中的下一个值,以得到另一个总和等于'10'。我不确定我的解释是否清楚,但我希望我能从中找到一些答案。 – loss

回答

1

这应该做你想什么。它显示每次总和等于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 
+1

谢谢@Tarun。这工作! – loss

+0

@loss更新了边界案例的解决方案! – Tarun

1

使用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启动指标

+0

好点,我编辑我的答案使用预先分配的二进制数组。 – user2999345

+0

谢谢@ user2999345 – loss

2

这可以使用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 
+0

谢谢@SardarUsama – loss