フィルターのクリア

How can I write a 'for' loop that sums up all elements of a vector?

35 ビュー (過去 30 日間)
Seif
Seif 2024 年 7 月 17 日 14:07
編集済み: Voss 2024 年 7 月 18 日 13:08
For instance, I have vector a = 1 2 3 4 5, or simply a=[1:5]. How can I write a 'for' loop that sums up all the elements while showing intermediate results? I want the last result to be 15, as in, 1+2+3+4+5. So far I've only managed to sum up elements like this: 1+2 = 3, 2+3 = 5 and so on. What I want is a 'for' loop that factors in the previous summation and sums it up with the next.
The code I've written so far is:
a= [1:5]
for i=1:5
c=sum(a(i)+a(i+1))
disp(c)
end
  1 件のコメント
VBBV
VBBV 2024 年 7 月 17 日 16:17
@Seif you could also simply sum up all the elements in vector as below
a= 1:5
a = 1x5
1 2 3 4 5
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
for i=1:5
c=a(1:i);
disp(['The sum is ',num2str(sum(c))])
end
The sum is 1 The sum is 3 The sum is 6 The sum is 10 The sum is 15

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

採用された回答

VBBV
VBBV 2024 年 7 月 17 日 14:18
@Seif do you mean like this ?
a= [1:5]
a = 1x5
1 2 3 4 5
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
for i=1:3
c(i)=sum(a(i)+a(i+1))
disp(sum(c))
end
c = 3
3
c = 1x2
3 5
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
8
c = 1x3
3 5 7
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
15
  1 件のコメント
Seif
Seif 2024 年 7 月 17 日 15:31
That works! Thank you so much

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

その他の回答 (1 件)

Voss
Voss 2024 年 7 月 17 日 14:33
a = 1:5;
total = 0;
for ii = 1:numel(a)
total = total+a(ii)
end
total = 1
total = 3
total = 6
total = 10
total = 15
  2 件のコメント
Seif
Seif 2024 年 7 月 17 日 15:30
Thank you so much!
Voss
Voss 2024 年 7 月 17 日 15:36
編集済み: Voss 2024 年 7 月 18 日 13:08
You're welcome! Any questions, let me know.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品


リリース

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by