如果我这样写:
clc
clear
close all
format long
fprintf( 1, 'Starting...\n' )
function results = do_thing()
results = 1;
end
results = do_thing()
用Octave
运行它,它工作正常:
Starting...
results = 1
但如果我尝试使用 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.
然后,如果我按如下方式修复错误:
clc
clear
close all
format long
fprintf( 1, 'Starting...\n' )
results = do_thing()
function results = do_thing()
results = 1;
end
它在 Matlab
上正常工作:
Starting...
results =
1
但是现在,它停止使用 Octave
:
Starting...
error: 'do_thing' undefined near line 8 column 11
error: called from
testfile at line 8 column 9
这个问题在这个问题上得到了解释:Run octave script file containing a function definition
如何在不必为函数 do_thing()
创建单独且独占的文件的情况下修复它?
此问题是否已在 2019a
等较新版本的 Matlab
上得到解决?
最佳答案
答案在评论中,但为了清楚起见:
% 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();
伴随解释性咆哮:
- 定义函数的规范和最安全的方法是在它们自己的文件中定义它们,并使该文件在 octave/matlab 的路径中可访问。
- Octave 几乎永远支持“动态”函数定义(即在脚本或命令行的上下文中)。然而,出于兼容性的考虑,由于 matlab 不支持这一点,所以大多数人没有使用它,而是相当明智地依赖于规范的方式。
- Matlab 最近也终于引入了动态函数定义,但已选择以破坏与 Octave 音程兼容性的方式显式实现它们,如您上面所述。 (咆哮:这可能是一个巧合,也是一个认真的设计决定,但我确实注意到,它也恰好违反了先前关于嵌套函数的 matlab 约定,允许在其封闭范围内的任何地方定义这些函数)。
- 从某种意义上说,一切都没有改变。 Matlab 与高级 Octave 功能不兼容,现在它已经引入了自己的此功能实现,它仍然不兼容。这是因祸得福。为什么?因为,如果您想要相互兼容的代码,您应该依赖规范的形式和良好的编程实践,而不是在您的脚本中乱扔动态函数,无论如何您都应该这样做。
关于matlab - 如何使用与 Matlab 脚本兼容的函数定义编写单个 Octave 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55770635/