如何编写具有与 Matlab 脚本兼容的函数定义的单个 Octave 脚本?

use*_*ser 4 matlab function octave

如果我这样写:

clc
clear

close all
format long
fprintf( 1, 'Starting...\n' )

function results = do_thing()
    results = 1;
end

results = do_thing()
Run Code Online (Sandbox Code Playgroud)

并使用 运行它Octave,它可以正常工作:

Starting...
results =  1
Run Code Online (Sandbox Code Playgroud)

但如果我尝试使用 运行它Matlab 2017b,它会抛出此错误:

Error: File: testfile.m Line: 13 Column: 1
Function definitions in a script must appear at the end of the file.
Move all statements after the "do_thing" function definition to before the first local function
definition.
Run Code Online (Sandbox Code Playgroud)

然后,如果我按如下方式修复错误:

Starting...
results =  1
Run Code Online (Sandbox Code Playgroud)

它可以正确运行在Matlab

Starting...

results =

     1
Run Code Online (Sandbox Code Playgroud)

但现在,它停止使用Octave

Starting...
error: 'do_thing' undefined near line 8 column 11
error: called from
    testfile at line 8 column 9
Run Code Online (Sandbox Code Playgroud)

这个问题在这个问题上得到了解释:运行包含函数定义的八度脚本文件

如何修复它,而无需为该函数创建单独的独占文件do_thing()

这个问题在某些较新版本的Matlabas上得到解决吗2019a

Tas*_*nou 5

答案在评论中,但为了清楚起见:

% in file `do_thing.m`
function results = do_thing()
    results = 1;
end

% in your script file
clc;   clear;   close all;   format long;
fprintf( 1, 'Starting...\n' );
results = do_thing();
Run Code Online (Sandbox Code Playgroud)

随附的解释性咆哮:

  • 定义函数的规范且最安全的方法是在它们自己的文件中定义它们,并使该文件可以在 Octave / Matlab 的路径中访问。
  • Octave 几乎永远支持“动态”函数定义(即在脚本或命令行的上下文中)。然而,出于兼容性的目的,由于matlab不支持这一点,因此大多数人没有使用它,而是相当明智地依赖于规范方式。
  • Matlab 最近也终于引入了动态函数定义,但选择以破坏与 Octave 兼容性的方式显式实现它们,如上所述。(咆哮:这可能是一个巧合,也是一个认真的设计决策,但我确实注意到,它也恰好违反了先前关于嵌套函数的 Matlab 约定,嵌套函数允许在其封闭范围内的任何位置定义)。
  • 从某种意义上说,一切都没有改变。Matlab 与高级八度音程功能不兼容,现在它已经引入了自己的此功能实现,但它仍然不兼容。这是因祸得福。为什么?因为,如果您想要互兼容的代码,您应该依赖规范的形式和良好的编程实践,而不是在脚本中乱扔动态函数,而这正是您应该做的