フィルターのクリア

Sum of following elements in array

1 回表示 (過去 30 日間)
Ivan Bioli
Ivan Bioli 2023 年 12 月 9 日
コメント済み: Walter Roberson 2023 年 12 月 9 日
Is there a faster way to do the following
s = rand(1, 10);
sum_following = zeros(length(s), 1);
for i = 1:length(s)-1
sum_following(i) = sum(s(i+1:end), 'all');
end
without doing
sum_following = sum(s,"all") - cumsum(s);
?
  9 件のコメント
Matt J
Matt J 2023 年 12 月 9 日
Because
1+eps^2 == 1
ans = logical
1
Walter Roberson
Walter Roberson 2023 年 12 月 9 日
The point is that doing this is fast but not numerically stable if the last entries of s are close to zero.
The loop with
sum(s(i+1:end), 'all');
is not numerically stable either. The trailing suffix [... A B -B -A] is going to come out as -A if abs(A) < eps(B)
Side note: You are using linear indexing. Linear indexing of anything always gives a vector result, and for a vector being added together, 'all' as a parameter does not provide any value.
Linear indexing of row vector: gives a row vector
Linear indexing of column ector: gives a column vector
Linear indexing of non-vectors: gives a result that is the same shape as the indices. Which, for i+1:end would be a row vector.

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

採用された回答

Matt J
Matt J 2023 年 12 月 9 日
編集済み: Matt J 2023 年 12 月 9 日
sum_following = cumsum([s(2:end),0],"reverse");

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by