登录论坛

查看完整版本 : 如何在MATLAB中正确使用递归?


poster
2019-12-14, 20:13
我有一个简单的m文件,它是作为递归函数创建的:

function[velocity] = terminal(m,c,t,vi) %inputs: % m = mass % c = coeffcient of drag % t = time % vi = initial velocity if t==18, velocity = vi+(9.8-c/m*(vi))*2; return end velocity = vi+(9.8-c/m*(vi))*2; velocity %used to print out velocity for debugging terminal(m,c,t+2,velocity); end 速度计算正确完成,因为它打印出每个递归。但是,最后返回的“ ans”是递归的第一个计算值。我的问题是如何递归正确设置matlab函数?还是可以做到,使用循环会更好吗?



回答:

忍受我,一段时间以来没有做过很多Matlab。

但是我只是简单地迭代调用您的函数:

velocity = vi for t = 0:2:18 velocity = velocity+(9.8-c/m*(velocity))*2; end 然后,对于每个t实例,它将计算给定初始速度的速度,并使用新的速度更新该值。

要使步长为2, 只需将步长添加到步长即可。 (http://cnx.org/content/m13258/1.3/)

更新以回应评论



更多&回答... (https://stackoverflow.com/questions/4760495)