How do I add the sum of 1st 3 elements of a vector in a for loop?

2 ビュー (過去 30 日間)
rezheen
rezheen 2025 年 6 月 12 日
編集済み: Stephen23 2025 年 6 月 12 日
I'd like for my for loop to end at n-1 as I have other code in the body. I just want to add a line in the for loop to add the sum of the 1st 3 elements underneath the left end points in the for loop and display it outside
t=0:5; a=[32 19.41 11.77 7.14 4.33 2.63];
n=length(a); a1=a(1:3);
S=0;
for k=1:n-1;
S=S+sum(a(k)); % left end-points = upper estimate because a is decreasing
end
disp(S)
I'd like the code to do this with the desired output:
S = 32+ 51.41 + 63.18 = 146.59
  2 件のコメント
Walter Roberson
Walter Roberson 2025 年 6 月 12 日
S=S+sum(a(1:k));
rezheen
rezheen 2025 年 6 月 12 日
In this case it's:
S=S+sum(a(1:k-2));
Thanks.

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

採用された回答

Stephen23
Stephen23 2025 年 6 月 12 日
編集済み: Stephen23 2025 年 6 月 12 日
a = [32,19.41,11.77,7.14,4.33,2.63];
m = 3;
s = sum(cumsum(a(1:m)))
s = 146.5900
or
s = a(1:m)*(m:-1:1).'
s = 146.5900
or
s = dot(a(1:m),m:-1:1)
s = 146.5900
or
s = sum(a(1:m).*(m:-1:1))
s = 146.5900
or
s = sum(a(1:m)*triu(ones(m)))
s = 146.5900
or
s = sum(repelem(a(1:m),m:-1:1))
s = 146.5900

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSparse Matrices についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by