Matlab:如何编写一个获取整数n并始终返回结果P的函数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))

查看:182
本文介绍了Matlab:如何编写一个获取整数n并始终返回结果P的函数P = 1 * 1.2 * 1.4 * .... *(1 + 0.2 *(n-1))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

但是它没有运行.如何使循环起作用?

But it does not run. How can I get the loop to work?

推荐答案

函数中的逻辑应类似于以下内容

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


紧凑版

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

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

这篇关于Matlab:如何编写一个获取整数n并始终返回结果P的函数P = 1 * 1.2 * 1.4 * .... *(1 + 0.2 *(n-1))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆