how to use loop for sum without using cumsum?
4 次查看(过去 30 天)
显示 更早的评论
采纳的回答
Aakash
2023-6-26
编辑:Aakash
2023-6-26
You can do this:
%sample data
x = [1, 2, 3, 4];
n = length(x);
s = zeros(n, 1); % Initialize s as a vector of zeros
for i = 1:n
s(i) = sum(x(1:i)) % Calculate the sum of the first i elements of x
end
or
s = zeros(n, 1); % Initialize s as a vector of zeros
s(1)=x(1);
for i = 2:n
s(i) = x(i)+s(i-1) % Calculate the sum of the first i elements of x
end
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!