Matlab:如何编写一个获取整数 n 且始终 returns 结果 P = 1*1.2*1.4*....*(1+0.2*(n-1)) 的函数

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))

我正在尝试解决一个问题,该问题需要编写一个名为 repeat_prod(n) 的函数,该函数获取一个整数 n 和 returns 以下函数的结果:

P = 1*1.2*1.4*....(1+0.2(n-1))

例如 n 为 6:

repeat_prod(6)

ans = 9.6768

我尝试了以下方法:

function P = repeat_prod(n)
  for 1:n-1
    P = (1+0.2*(n-1));
  end
end

但它没有 运行。我怎样才能让循环工作?

函数中的逻辑应该如下所示

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

精简版

您还可以在函数 repeat_prod 中使用 prod 来替换 for 循环,即

function P = repeat_prod(n)
  P = prod(1 + 0.2*((1:n)-1));
end