MatLab递归错误(初学者)
好的。 所以我在 MatLab 中有两个互相调用的函数。
Riemann.m
function I = Riemann(f, dx, a, b)
x = a:dx:b;
fx = f(x).*dx;
I = sum(fx);
和 myfunc.m
function f = myfunc(x)
f = sin(1./x);
for n=1:100
I = Riemann(@myfunc, 0.001, 1/n, 1);
end
plot(I)
问题是让它运行。 我如何调用 myfunc 来从中获取任何内容。 我尝试过的所有内容最终都会陷入无休止的递归调用堆栈(这是有道理的)。
Ok. So i've got two function in MatLab that are calling each other.
Riemann.m
function I = Riemann(f, dx, a, b)
x = a:dx:b;
fx = f(x).*dx;
I = sum(fx);
and myfunc.m
function f = myfunc(x)
f = sin(1./x);
for n=1:100
I = Riemann(@myfunc, 0.001, 1/n, 1);
end
plot(I)
The problem is getting that to run. How do I call myfunc to get anything out of that. Everything I've tried ends up in an endless recursive call stack (which makes sense).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的问题在于函数的定义:为了能够使用递归定义,您必须能够计算两个函数中的至少一个而无需另一个,至少对于某些值而言。 您还必须确保每次计算最终都依赖于无需递归即可获得的结果。
对于您的具体问题,我感觉您想要积分函数 f(x)=sin(1./x)。 如果是这样,第二个函数的代码应为:
Your problem is with the definition of your functions: to be able to work with recursive definition, you must be able to compute at least one of the two function without the other, at least for some values. You must also make sure that every computation will end up relying on these result you can obtain without recursion.
For your specific problem, I have the feeling you want to integrate the function f(x)=sin(1./x). If so, the code of your second function should read:
函数 myfunc 没有在
f = sin(1./x);
之后结束。 在那里终止该函数并从其他地方(单独的文件)调用绘图代码。来自手册:
您可以使用 end 语句终止任何函数,但在大多数情况下,这是可选的。 仅在使用一个或多个嵌套函数的 M 文件中才需要 end 语句。 在这样的 M 文件中,每个函数(包括主函数、嵌套函数、私有函数和子函数)都必须以 end 语句终止。 您可以使用 end 终止任何函数类型,但除非 M 文件包含嵌套函数,否则不需要这样做。
The function myfunc does not end after
f = sin(1./x);
where it should. Terminate the function there and call the plotting code from elsewhere (separate file).From manual:
You can terminate any function with an end statement but, in most cases, this is optional. end statements are required only in M-files that employ one or more nested functions. Within such an M-file, every function (including primary, nested, private, and subfunctions) must be terminated with an end statement. You can terminate any function type with end, but doing so is not required unless the M-file contains a nested function.
当 myFunc 停止调用黎曼时,您需要输入 x 的最终条件。 将实际函数(在本例中为 sin)发送给 Riemann 比调用 myFunc 更好。
You need a final condition for input x when myFunc stops calling Riemann. Also sending the actual function(in this case sin) to Riemann is a better idea than calling myFunc.