如何检测我是否正在运行MATLAB或Octave?

55

我需要编写能够在Octave和MATLAB中运行的代码。问题是它需要处理一些GUI相关的内容,而MATLAB和Octave的处理方式完全不同。

有没有办法检测我是否在运行MATLAB或Octave,以便调用正确的函数?

4个回答

55

你可以使用以下测试来区分 Octave 和 MATLAB:

isOctave = exist('OCTAVE_VERSION', 'builtin') ~= 0;

1
不错的想法,但将其封装在一个函数中会更好。 - Richie Cotton
哎,'OCTAVE_VERSION','builtin'的存在在我的matlab和octave上都评估为0 :-( 。在检查之前我已经给这个答案点赞了,糟糕。 - foobarbecue
2
@foobarbecue 运行良好(刚刚尝试了一下),同样的测试甚至包含在官方的 Octave 手册中:https://octave.org/doc/latest/How-to-Distinguish-Between-Octave-and-Matlab.html - Amro
嗯,我的环境可能出了点问题。现在可以工作了。 - foobarbecue

24
在官方octave.org网站的维基中也有hint。他们提出了以下建议:
编辑:并非所有版本的Matlab都支持“#”作为注释,因此我将示例更改为使用“%”。它适用于Matlab R2018(Linux)和Octave 4.2.2
function foo
  %% fancy code that works in both
  if (is_octave)
    %% use octave super_powers
  else
    %% do it matlab way
  end
  %% fancy code that works in both
end

%% subfunction that checks if we are in octave
function r = is_octave ()
  persistent x;
  if (isempty (x))
    x = exist ('OCTAVE_VERSION', 'builtin');
  end
  r = x;
end

3
“R2018”不是MATLAB的版本号,应该是R2018a或R2018b。 - Cris Luengo

5
我会使用例如ver命令,其结果如下:
在MATLAB中:

MATLAB Version 7.7.0.471 (R2008b) Operating System: Linux 2.6.31-20-generic #57-Ubuntu SMP Mon Feb 8 09:05:19 UTC 2010 i686 Java VM Version: Java 1.6.0_04 with Sun Microsystems Inc. Java HotSpot(TM) Client VM mixed mode


在Octave中:

GNU Octave Version 3.0.5 GNU Octave License: GNU General Public License Operating System: Linux 2.6.31-20-generic #57-Ubuntu SMP Mon Feb 8 09:05:19 UTC 2010 i686


另一个可能的方法是使用license函数。

4

在Matlab中:

>> exist __octave_config_info__
ans =
     0

在Octave中:

octave:3> exist __octave_config_info__
ans =  5

在Octave语法上有挑战性的人(比如我),可以在if语句中使用exist('octave_config_info')... - Rhys Ulerich
2
实际上,我在Matlab和Octave中都得到了ans = 0的结果! - winkmal
1
@winkmal 尝试使用 exist __octave_config_info__ 而不是 octave_config_info,因为 octave_config_info 已过时。更多信息请查看此处 - Foad S. Farimani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接