summation using while loop until I get a certain value

hello,I am asked to sum the elements of an array until I get a certain value. I used the while loop but when I run the code it says that index exceeds matrix dimensions. Here is my code,
A=[3 4 10 3 9 10 12 4 11 9 11 10];
sum=0;
k=1:length(A);
while sum<43
sum=sum+A(k);
k=k+1;
end
disp(sum);
disp(k);
what could be the problem with this code? thanks...

1 件のコメント

Stephen23
Stephen23 2015 年 11 月 15 日
編集済み: Stephen23 2015 年 11 月 16 日
Note that you should not call your variable sum, as this is the name of the inbuilt and very important function sum. When you define a variable/function named sum, it shadows the inbuilt function and stops it from working. This will break a lot of code!

サインインしてコメントする。

回答 (2 件)

Stephen23
Stephen23 2015 年 11 月 15 日

2 投票

This is much easier without any loops:
>> N = 43;
>> A = [3,4,10,3,9,10,12,4,11,9,11,10];
>> B = cumsum(A);
>> C = B(B<N);
>> C(end)
ans =
39
Andrei Bobrov
Andrei Bobrov 2015 年 11 月 15 日

1 投票

A=[3 4 10 3 9 10 12 4 11 9 11 10];
sum1=0;
k=1;
while sum1<43
sum1=sum1+A(k);
k=k+1;
end
disp(sum1);
disp(k);

2 件のコメント

dilara ozbay
dilara ozbay 2015 年 11 月 15 日
k=k+1 must be above the sum1 equation.. thanks:)
Andrei Bobrov
Andrei Bobrov 2015 年 11 月 16 日
A=[3 4 10 3 9 10 12 4 11 9 11 10];
sum1=0;
k=1;
s = [];
while sum1 < 43
s =sum1;
sum1=sum1+A(k);
k=k+1;
end
disp(s);
disp(k-1);

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2015 年 11 月 15 日

コメント済み:

2015 年 11 月 16 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by