运行包含功能定义的八度脚本文件
我有一个非常新的八度问题。
在Octave控制台中运行此代码正常:
function fibo = recfibo(n)
if ( n < 2 )
fibo = n;
else
fibo = recfibo(n-1) + recfibo(n-2);
endif
endfunction
disp(recfibo(5))
通过将此代码插入为 file.m 的外部文件中,并通过 octave file.m
执行它。 :
警告:功能名称'recfibo'不同意函数文件名 '/users/admin/google drive/file.m' 错误:'n'未定义附近的第2列第8列错误:从 第2列第3行的八度
我应该如何解决此特定问题?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
添加
1;
作为文件的第一行:以函数定义开头的任何M文件是函数M文件,而不是脚本M文件。通过向顶部添加毫无意义的语句,您可以将其变成脚本。
在MATLAB中(从最近出现)中,脚本M文件可以在脚本末尾定义函数。在那里,您将
disp
行放在文件的顶部,并在末尾将函数
块放置,而没有任何脚本行。但是,八度需要在使用它们之前定义函数,因此必须在使用该函数的脚本行之前。八度允许在MATLAB引入该功能之前的脚本文件中的函数定义,因此它们的实现与MATLAB的功能不兼容。Add
1;
as the first line of the file:Any M-file that starts with a function definition is a function M-file, not a script M-file. By adding a meaningless statement to the top, you turn it into a script.
In MATLAB (since fairly recently), a script M-file can define functions at the end of the script. There you'd put the
disp
line at the top of the file, and have thefunction
block at the end, without any script lines after it. However, Octave requires functions to be defined before you use them, hence it has to come before the script line that uses the function. Octave allowed the definition of functions within a script file before MATLAB introduced that feature, hence their implementation is not compatible with that of MATLAB.如@crisluengo提供的答案所述,您已经创建了一个函数文件,而不是脚本文件,并且对其进行处理
在八度中
不同。因为它是一个函数文件octave通过调用其定义的 no gram>和nargout = 0
的函数来执行它。因此,您将遇到一个错误,即n
不确定。另一个问题是函数名称
'recfibo'
不同意函数文件名'file'
。在这种情况下,八度在内部将函数的名称更改为功能文件的名称,以便将名称更改为'file'
。因此,八度函数本身会忘记原始功能名称,不幸的是,该函数无法递归地调用自己!我喜欢@crisluengo的答案,但我认为使用函数文件而不是脚本文件的愚蠢和优选的方法是 emansey ,尽管脚本文件解决方案是 onlylly 在先前的八倍版本中起作用的解决方案八度3.x)。
您可以将代码更改为:
As stated in the answer provided by @CrisLuengo here you have created a function file instead of a script file and they are treated
differently
in Octave. Because it is a function file Octave executes it by calling the function it defines with no arguments andnargout = 0
. So you will get an error thatn
is undefined.Another problem is that the function name
'recfibo'
does not agree with function filename'file'
. In such cases Octave internally changes the name of the function to the name of the function file so the name is changed to'file'
. Therefor Octave and the function itself will forget the original function name and unfortunately the function cannot call itself recursively!I like the @CrisLuengo 's answer but I think the more idiomatic and preferable way is always using function files instead of script files, though the script file solution is the only solution that works in previous Octave versions (Octave 3.X).
You can change your code to: