问题
I am trying to solve a problem that requires writing a function called repeat_prod(n), that gets an integer n and returns the result of the following function:
P = 1*1.2*1.4*....(1+0.2(n-1))
for exemple if n is 6:
repeat_prod(6)
ans = 9.6768
I tried the following:
function P = repeat_prod(n)
for 1:n-1
P = (1+0.2*(n-1));
end
end
But it does not run. How can I get the loop to work?
回答1:
The logic within your function should be something like below
function P = repeat_prod(n)
P = 1; % initial value for following cumulative products
for k = 1:n
P = P*(1+0.2*(k-1));
end
end
Compact Version
You can also use prod
within your function repeat_prod
to replace for
loop, i.e.,
function P = repeat_prod(n)
P = prod(1 + 0.2*((1:n)-1));
end
来源:https://stackoverflow.com/questions/61159947/matlab-how-to-write-a-function-that-gets-an-integer-n-and-always-returns-the-re