summing up array element

Hello,
I am new to programming, I have an array like p = [3 6 2 5];
I need c = [3 9 11 16]; First element in the array is as it is, when it goes to next element it has to sum the previous element.
Regards, SBN

1 件のコメント

Jan
Jan 2013 年 7 月 25 日
Is this a homework question?

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

回答 (4 件)

Cedric
Cedric 2013 年 7 月 25 日
編集済み: Cedric 2013 年 7 月 25 日

2 投票

Hi, use CUMSUM:
>> p_csum = cumsum(p)
p_csum =
3 9 11 16

2 件のコメント

Bathrinath
Bathrinath 2013 年 7 月 25 日
Thanks it works. Can you give the solution in for loop .
Cedric
Cedric 2013 年 7 月 25 日
編集済み: Cedric 2013 年 7 月 25 日
Did you try building a solution based on a FOR loop? What did you implement so far?

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

Evan
Evan 2013 年 7 月 25 日
編集済み: Evan 2013 年 7 月 25 日

1 投票

help cumsum
>> s = cumsum(p)
s =
3 9 11 16

1 件のコメント

Bathrinath
Bathrinath 2013 年 7 月 25 日
Thanks it works. Can you give the solution in for loop .

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

Andrew Reibold
Andrew Reibold 2013 年 7 月 25 日
編集済み: Andrew Reibold 2013 年 7 月 25 日

1 投票

Here is your solution in a really easy loop.
p = [3 6 2 5]; %Can have as many numbers as you want
for n = 2:length(p) %n can be whatever counter you want.
p(n) = p(n)+p(n-1); %semi-colon suppresses output
end
-Andrew

1 件のコメント

Bathrinath
Bathrinath 2013 年 7 月 25 日
Thanks it works

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

Iain
Iain 2013 年 7 月 25 日
編集済み: Iain 2013 年 7 月 25 日

0 投票

for i = 1:numel(p)
c(i) = sum(p(1:i));
end
Or
so_far = 0;
for i = 1:numel(p)
so_far = so_far + p(i);
c(i) = so_far;
end
or
for i = 1:numel(p)
s = 0;
for j = 1:i
s = s+ p(j);
end
c(i) = s;
end

1 件のコメント

Jan
Jan 2013 年 7 月 25 日
These are inefficient solutions, because the complete sum is calculated in each iteration. While this might not matter for 4 elements, the runtime will grow rapidly for longer data.
It is more efficient to re-use the sum for the elements 1 to i, when the sum until the i+1.th element is obtained. See Andrews answer.

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

カテゴリ

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

タグ

質問済み:

2013 年 7 月 25 日

編集済み:

2021 年 9 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by