运行包含函数定义的八度脚本文件 [英] Run octave script file containing a function definition

查看:216
本文介绍了运行包含函数定义的八度脚本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常新手的八度音阶问题.
在八度控制台中运行此代码可以正常工作:

I've a very newbie octave question.
Running this code in octave console is working fine:

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执行该代码,将发生错误:

By inserting this code in an external file named for example file.m, and executing it through octave file.m an error occurs:

警告:函数名称"recfibo"与函数文件名不一致 '/Users/admin/Google Drive/file.m' 错误:在第2行第8列附近未定义'n'错误:从调用 第2行第3列的八度音阶

warning: function name 'recfibo' does not agree with function filename '/Users/admin/Google Drive/file.m' error: 'n' undefined near line 2 column 8 error: called from octave at line 2 column 3

我应该如何解决这个特殊问题?

How should I resolve this particular problem?

推荐答案

如@CrisLuengo提供的答案所述,您已经创建了一个功能文件而不是脚本文件,并且将它们视为

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 and nargout = 0. So you will get an error that n is undefined.

另一个问题是函数名称'recfibo'与函数文件名'file'不符.在这种情况下,Octave在内部将函数的名称更改为函数文件的名称,因此名称被更改为'file'.因此,Octave和函数本身会忘记原来的函数名,不幸的是该函数无法递归调用它!

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!

我喜欢@CrisLuengo的答案,但我认为更惯用和可取的方法是始终使用功能文件而不是脚本文件,尽管脚本文件解决方案是

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

您可以将代码更改为:

function file
    disp(recfibo(5))
endfunction
function fibo = recfibo(n)
    if ( n < 2 )
        fibo = n;
    else
        fibo = recfibo(n-1) + recfibo(n-2);
    endif
endfunction

这篇关于运行包含函数定义的八度脚本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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