MATLAB Programming/Differences between Octave and MATLAB

From Wikibooks, open books for an open world
Jump to: navigation, search



Octave has been mainly built with MATLAB compatibility in mind. It has a lot of features in common with MATLAB:

  1. Matrices as fundamental data type.
  2. Built-in support for complex numbers.
  3. Powerful built-in math functions and extensive function libraries.
  4. Extensibility in the form of user-defined functions.

Some of the differences that do exist between Octave and MATLAB can be worked around using "user preference variables."[1]

GNU Octave is mostly compatible with Matlab. However, Octave's parser allows some (often very useful) syntax that Matlab's does not, so programs written for Octave might not run in Matlab. For example, Octave supports the use of both single and double quotes. Matlab only supports single quotes, which means parsing errors will occur if you try to use double quotes (e.g. in an Octave script when run on Matlab). Octave and Matlab users who must collaborate with each other need to take note of these issues and program accordingly.

Note: Octave can be run in "traditional mode" (by including the --traditional flag when starting Octave) which makes it behave in a slightly more Matlab-compatible way.

This chapter documents instances where Matlab's parser will fail to run code that will run in Octave, and instances where Octave's parser will fail to run code that will run in Matlab. This page also contains notes on differences between things that are different between Octave (in traditional mode) and Matlab.

Tip for sharing .mat files between Octave and Matlab: always use save -V6 if you are using Matlab 7.X. Octave version 2.1.x cannot read Matlab 7.X .mat files. Octave 2.9.x can read Matlab 7.X .mat files.

Contents

[edit] Load

For compatiblility, it is best to specify absolute paths of files for LOAD. Matlab (7.0) vs Octave (2.1.71): paths are not searched for .mat files in the same way as .m files:

Matlab
 a = 1; save /tmp/a.mat a ; addpath('/tmp'); load a.mat 
 % OK
 
Octave
 a = 1; save /tmp/a.mat a ;   
 LOADPATH=['/tmp:',LOADPATH];
 load a.mat 
 % error: load: nonexistent file: `a.mat'

For any other purpose, don't use absolute paths. It is bad programming style. Don't do it. It causes many problems.

[edit] C-Style Autoincrement and Assignment operators

Octave (3.0.1) supports C-style autoincrement and assignment operators:

  i++; ++i; i+=1; etc.

MatLab (7.0) does not.

[edit] Temporaries

Octave supports temporary expressions.

  columns = size(mtx)(2);   %  works in Octave, fails in Matlab
  tmp = size(mtx);
  columns = tmp(2);         %  works in both

[edit] product of booleans

Matlab (7.0) and Octave (3.0.2) responds differently when computing the product of boolean values:

  X = ones(2,2) ; prod(size(X)==1) 

  Matlab: ??? Function 'prod' is not defined for values of class 'logical'.
  Octave: ans = 0

[edit] nargin

Matlab (7.0) will not allow the following; Octave (2.1.71) will.

 function a = testfun(c)
  if (nargin == 1)
   nargin = 2;
  end

[edit] startup.m

Matlab will execute a file named 'startup.m' in the directory it was called from on the command line. Octave does not. It will, however, execute a file named '.octaverc' which can be edited to execute existing files

if ( exist ('startup.m', 'file') )
  source ('startup.m')  # load startup.m like matlab
endif

[edit] ['abc ';'abc']

['abc ';'abc'] is allowed in Octave; Matlab returns: ?? Error using ==> vertcat

In Octave the result will be a 2 by 4 matrix where the last element of the last row is a space.

[edit] Calling Shells

the "! STRING" syntax calls a shell with command STRING in Matlab. Octave does not recognize !. Always use system(STRING) for compatibility.

If you really miss the one-character shortcut, for convenience on the command line you can create a similar shortcut by defining the following in your 2.9.x octave startup file:

  function S(a), system(a); end
  mark_as_rawcommand('S')

Now "S STRING" will evaluate the string in the shell.

[edit] hist

hist.m in Octave has a normalization input, Matlab does not.

[edit] Getting Version Information

Octave (2.1.7X) uses "OCTAVE_VERSION", Matlab uses "ver" for version informaton. (Octave 2.9.5 and later has "ver", so is compatible in this sense.)

[edit] Format of printing to screen

Cell arrays and structures print to screen in different format. There may be switches to make them the same, for example, struct_levels_to_print. None are set in --traditional mode, however.

[edit] Attempting to load empty files

MATLAB lets you load empty files, OCTAVE does not.

system('touch emptyfile') ; A = load('emptyfile')

  Matlab 6.5    : A=[]
  Octave 2.1.71 : error: load: file `emptyfile' seems to be empty!
                  error: load: unable to extract matrix size from file `emptyfile'


[edit] fprintf and printf

Matlab doesn't support `printf' as a command for printing to the screen.

   foo = 5;
   printf('My result is: %d\n', foo)

works in Octave, but not Matlab. If using Matlab, `fprintf' covers writing both to the screen and to a file:

   foo = 5;
   fprintf('My result is: %d\n', foo)

In Matlab, the omission of the optional file-handle argument to fprintf (or using the special value 1 for standard output or 2 for standard error) causes the text to be printed to the screen rather than to a file.

[edit] Whitespace

Matlab doesn't allow whitespace before the transpose operator.

   [0 1]'

works in Matlab, but

   [0 1] '

doesn't. Octave allows both cases.

[edit] Line continuation

Matlab always requires `...' for line continuation.

   rand (1, ...
         2)

while both

   rand (1,
         2)

and

   rand (1, \
         2)

work in Octave, in addition to `...'.



[edit] Logical operators (And, Or, Not)

Octave allows users to use two different group of logical operators: the ones used in Matlab, or the ones familiar to C/Java/etc programmers. If you use the latter, however, you'll be writing code that Matlab will not accept, so try to use the Matlab-compatible ones:

  • For not-equal comparison, Octave can use '~=' or '!='. Matlab requires '~=' .
  • For a logical-and, Octave can use `&' or `&&'; Matlab requires `&' . (note: Matlab supports `&&' and `||' as short-circuit logical operators since version 6.5.)
  • For a logical-or, Octave can use `|' or `||'; Matlab requires `|' . (note: Octave's '||' and '&&' return a scalar, '|' and '&' return matrices)

[edit] Octave Controls System Toolbox

Both MATLAB and Octave have toolboxes intended to control system design. In Octave, the toolbox is called the Octave Controls System Toolbox. Users of Debian and its derivatives can install it by installing the package "octave-control", if it is not installed by default.

In Octave, initialization of a system data structure (simply, a system model) works very much as in MATLAB: one can use tf, ss or zp commands in order to initialize a system data structure in form of a transfer function, state space model or zero-pole representation. However, while in MATLAB one may write simply F = G + H to sum up two systems or F = G*H to connect two systems in series, in Octave for that purpose one have to use sysadd/syssub and sysmult, respectively.

For more information about functions' syntax, type help <name of function>. For more information about the Controls System Toolbox, start the Octave Controls System Toolbox Demo demo/tutorial program by typing DEMOcontrol in Octave command prompt.

Example code in MATLAB:

 F = G + H

Code in Octave doing the same:

 F = sysadd(G, H)

Both approaches seems to work analogous, though MATLAB's looks a bit more clear. Hopefully, that would be fixed in future versions of Octave, since one of its primary goals is to wholly support the syntax of MATLAB. But there is no guarantee, and even no note about any attempt has yet been published.

[edit] Some other differences

  • MATLAB uses the percent sign '%' to begin a comment. Octave uses both the hash symbol '#' and the percent sign '%' interchangeably.
  • For exponentiation, Octave can use `^' or `**'; Matlab requires `^'.
  • For string delimiters, Octave can use ' or "; Matlab requires '.
  • For ends, Octave can use `end{if,for, ...}'; Matlab requires `end'.
  • Octave supports C-style hexadecimal notation (e.g. "0xF0"); Matlab requires the hex2dec function (e.g. "hex2dec('F0')").
  • If something (like Netlab) need a function called fcnchk, you can just put the following into a file called fcnchk.m and put it somewhere Octave can find it:
function f=fcnchk(x, n)
  f = x;
end
  • The main difference is the lack of GUI for Octave. There are several attempts to solve this issue ( Xoctave, QtOctave, guioctave, etc.)

[edit] Notes about specific functions

  • For datetick, use gnuplot commands:
 __gnuplot_set xdata time 
 __gnuplot_set timefmt "%d/%m" 
 __gnuplot_set format x "%b %d"
  • datestr function: There used to be a difference in datestr between Octave-forge and Matlab. Has this been changed?
  • For "dbstep, in" use "dbstep"; for "dbstep", use "dbnext"
  • For "eig(A,B)" use "qz(A,B)"
  • fputs function is not available in MATLAB. Use fprintf instead.
  • load in Matlab = load --force in Octave (should --force be default in --traditional?)
  • page_output_immediately = 1 should this be default in --traditional?
  • strread and textscan in Octave 3.4.0 are not fully compatible with their implementations in Matlab 2009b (and probably later versions as well). For instance, the N=-1 option (repeat reading format until end of string) is not implemented in Octave 3.4.0 . Using a value of N=a positive integer (read format N times) does work the same as in Matlab.
  • textscan function is not included in Octave versions prior to 3.4.0 . Use fscanf instead.
  • In Octave, one can specify data labels (or legends) with the plot function, while in Matlab, one can only use the legend function.
Octave:        plot(x, y, ';label;')
Matlab/Octave: plot(x, y); legend('label')
  • The error(msg) function in Matlab is a no-op if the message is empty. In Octave, it results in an error.

[edit] References

[edit] See also

Personal tools
Namespaces

Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export