Matlab: How to write a function that gets an integer n and always returns the result P = 1*1.2*1.4*…*(1+0.2*(n-1))

懵懂的女人 提交于 2020-06-09 07:03:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!