How to write cumulative product function

1 次查看(过去 30 天)
Hi
I am trying to implement cumproduct without using built-in function. Below is my test code . I need help to implement "My Test code " like built-in cumprod([1 1 2 : 5]).
Thank you!!
% Built-in
A = cumprod([1 1 2 : 5])
% A
%------+
% 1
% 1
% 2
% 6
% 24
% 120
% My Test code ,
A1 = 1;
for i = 1 :5
A1 = A1 * i;
fprintf('%10d|%10d|\n',i,A1);
end
A1
-----+
1|
2|
6|
24|
120|

采纳的回答

Torsten
Torsten 2022-3-16
编辑:Torsten 2022-3-16
m = 10;
v = [1 1 2:m];
pcum = cumproduct(v)
function pcum = cumproduct(v)
n = numel(v);
pcum = zeros(n,1);
pcum(1) = v(1);
for i = 2:n
pcum(i) = pcum(i-1)*v(i);
end
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by