manpagez: man pages & more
info Octave-FAQ
 Home | html | info | man
 [ < ] [ > ] [ << ] [ Up ] [ >> ] [Top] [Contents] [Index] [ ? ]

# 11. Porting programs from MATLAB to Octave

“I wrote some code for MATLAB, and I want to get it running under Octave. Is there anything I should watch out for?”

or alternatively

“I wrote some code in Octave, and want to share it with MATLAB users. Is there anything I should watch out for?”

which is not quite the same thing. There are still a number of differences between Octave and MATLAB, however in general differences between the two are considered as bugs. Octave might consider that the bug is in MATLAB and do nothing about it, but generally functionality is almost identical. If you find a difference between Octave behavior and MATLAB, then you should send a description of this difference (with code illustrating the difference, if possible) to bug@octave.org.

Furthermore, Octave adds a few syntactical extensions to Matlab that might cause some issues when exchanging files between Matlab and Octave users. As both Octave and MATLAB are under constant development the information in this section is subject to change at anytime.

You should also look at the page http://octave.sourceforge.net/packages.html and http://octave.sourceforge.net/doc/ that has a function reference that is up to date. You can use this function reference to see the number of octave function that are available and their MATLAB compatibility.

The major differences between Octave 3.2.N and MATLAB R2008a are:

• Nested Functions

Octave doesn't yet have nested functions. That is

 ```function y = foo (x) y = bar(x) function y = bar (x) y = …; end end ```

There was discussion in Octave of having these even prior to MATLAB, and the decision was made not to have these in Octave at the time for compatibility. The above written with sub-functions functions would be

 ```function y = foo (x) y = bar(x) end function y = bar (x) y = …; end ```

Now that MATLAB has recently introduced nested functions, Octave will probably have them soon as well. Until then nested functions in Octave are treated as sub-functions with the same scoping rules as sub-functions.

The authors of Octave consider the nested function scoping rules of Matlab to be more problems than they are worth as they introduce diffiult to find bugs as inadvertantly modifying a variable in a nested function that is also used in the parent is particularly easy.

• Differences in core syntax There a few core MATLAB syntaxes that are not accepted by Octave, these being
• Some limitations on the use of function handles. The major difference is related to nested function scoping rules (as above) and their use with function handles.
• Some limitations of variable argument lists on the LHS of an expression, though the most common types are accepted.
• MATLAB classdef object oriented programming is not yet supportted, though work is underway and when development more on to Octave 3.3 this will be included in teh development tree.
• Differences in core functions A large number of the MATLAB core functions (ie those that are in the core and not a toolbox) are implemented, and certainly all of the commonly used ones. There are a few functions that aren't implemented, for example `condest` or to do with specific missing Octave functionality (gui, dll, java, activex, dde, web, and serial functions). Some of the core functions have limitations that aren't in the MATLAB version. For example the `sprandn` function can not force a particular condition number for the matrix like MATLAB can.
• Just-In-Time compiler MATLAB includes a "Just-In-Time" compiler. This compiler allows the acceleration of for-loops in MATLAB to almost native performance with certain restrictions. The JIT must know the return type of all functions called in the loops and so you can't include user functions in the loop of JIT optimized loops. Octave doesn't have a JIT and so to some might seem slower than MATLAB. For this reason you must vectorize your code as much as possible. The MathWorks themselves have a good document discussing vectorization at http://www.mathworks.com/support/tech-notes/1100/1109.html.
• Compiler On a related point, there is no Octave compiler, and so you can't convert your Octave code into a binary for additional speed or distribution. There is an example of how to do this at http://www.stud.tu-ilmenau.de/~rueckn/, but this is a very early example code and would need lots of work to complete it.
• Graphic Handles Up to Octave 2.9.9 there was no support for graphic handles in Octave itself. In the 3.2.N versions of Octave the support for graphics handles is converging towards full compatibility. The `patch` function is currently limited to 2-D patches, due to an underlying limitation in gnuplot.
• GUI There are no MATLAB compatible GUI functions. There are a number of bindings from Octave to Tcl/Tk, Vtk and zenity included in the Octave Forge project (http://octave.sourceforge.net) for example that can be used for a GUI, but these are not MATLAB compatible. Work on a matlab compatible GUI is in an alpha stage in the JHandles package (http://octave.sourceforge.net/jhandles/index.html). This might be an issue if you intend to exchange Octave code with MATLAB users.
• Simulink Octave itself includes no Simulink support. Typically the simulink models lag research and are less flexible, so shouldn't really be used in a research environment. However, some MATLAB users that try to use Octave complain about this lack. There is a similar package to simulink for the Octave and R projects available at http://www.scicraft.org/
• Mex-Files Octave includes an API to the matlab MEX interface. However, as MEX is an API to the internals of MATLAB and the internals of Octave differ from MATLAB, there is necessarily a manipulation of the data to convert from a MEX interface to the Octave equivalent. This is notable for all complex matrices, where MATLAB stores complex arrays as real and imaginary parts, whereas Octave respects the C99/C++ standards of co-locating the real/imag parts in memory. Also due to the way MATLAB allows access to the arrays passed through a pointer, the MEX interface might require copies of arrays (even non complex ones).
• Block comments Block comments denoted by "%{" and "%}" markers are supported by Octave with some limitations. The major limitation is that block comments are not supported within [] or {}.
• Mat-File format There are some differences in the mat v5 file format accepted by Octave. MATLAB recently introduced the "-V7.3" save option which is an HDF5 format which is particularly useful for 64-bit platforms where the standard matlab format can not correctly save variables.. Octave accepts HDF5 files, but is not yet compatible with the "-v7.3" versions produced by MATLAB.

Although Octave can load inline abd function handles saved by MATLAB, it can not yet save them.

Finally, Some multi-byte unicode characters aren't yet treated in mat-files.

• Profiler Octave doesn't have a profiler. Though there is a patch for a flat profiler, that might become a real profiler sometime in the future. see the thread

for more details

• Toolboxes Octave is a community project and so the toolboxes that exist are donated by those interested in them through the Octave Forge website (http://octave.sourceforge.net). These might be lacking in certain functionality relative to the MATLAB toolboxes, and might not exactly duplicate the matlab functionality or interface.
• Short-circuit & and | operators The `&` and `|` operators in MATLAB short-circuit when included in an if statemant and not otherwise. In Octave only the `&&` and `||` short circuit. Note that this means that  ``` if (a | b) … end ```

and

 ``` t = a | b; if t … end ```

are different in MATLAB. This is really a MATLAB bug, but there is too much code out there that relies on this behavior to change it. Prefer the || and && operators in if statements if possible.

Note that the difference is also significant when either argument is a function with side effects or if the first argument is a scalar and the second argument is an empty matrix. For example, note the difference between

 ``` t = 1 | []; ## results in [], so... if (t) 1, end ## in if ([]), this is false. ```

and

 ``` if (1 | []) 1, end ## short circuits so condition is true. ```

Another case that is documented in the MATLAB manuals is that

 ``` t = [1, 1] | [1, 2, 3]; ## error if ([1, 1] | [1, 2, 3]) 1, end ## OK ```

Also MATLAB requires the operands of && and || to be scalar values but Octave does not (it just applies the rule that for an operand to be considered true, every element of the object must be nonzero or logically true).

Finally, note the inconsistence of thinking of the condition of an if statement as being equivalent to `all(X(:))` when X is a matrix. This is true for all cases EXCEPT empty matrices:

 ``` if ([0, 1]) == if (all ([0, 1])) ==> i.e., condition is false. if ([1, 1]) == if (all ([1, 1])) ==> i.e., condition is true. ```

However,

 ``` if ([]) != if (all ([])) ```

because `samp ([]) == 1` (because, despite the name, it is really returning true if none of the elements of the matrix are zero, and since there are no elements, well, none of them are zero). But, somewhere along the line, someone decided that if `([])` should be false. Mathworks probably thought it just looks wrong to have `[]` be true in this context even if you can use logical gymnastics to convince yourself that "all" the elements of a matrix that doesn't actually have any elements are nonzero. Octave however duplicates this behavior for if statements containing empty matrices.

• Solvers for singular, under- and over-determined matrices

Matlab's solvers as used by the operators mldivide (\) and mrdivide (/), use a different approach than Octave's in the case of singular, under-, or over-determined matrices. In the case of a singular matrix, Matlab returns the result given by the LU decomposition, even though the underlying solver has flagged the result as erroneous. Octave has made the choice of falling back to a minimum norm solution of matrices that have been flagged as singular which arguably is a better result for these cases.

In the case of under- or over-determined matrices, Octave continues to use a minimum norm solution, whereas Matlab uses an approach that is equivalent to

 ```function x = mldivide (A, b) [Q, R, E] = qr(A); x = [A \ b, E(:, 1:m) * (R(:, 1:m) \ (Q' * b))] end ```

While this approach is certainly faster and uses less memory than Octave's minimum norm approach, this approach seems to be inferior in other ways.

A numerical question arises: how big can the null space component become, relative to the minimum-norm solution? Can it be nicely bounded, or can it be arbitrarily big? Consider this example:

 ```m = 10; n = 10000; A = ones(m, n) + 1e-6 * randn(m,n); b = ones(m, 1) + 1e-6 * randn(m,1); norm(A \ b) ```

while Octave's minimum-norm values are around 3e-2, Matlab's results are 50-times larger. For another issue, try this code:

 ```m = 5; n = 100; j = floor(m * rand(1, n)) + 1; b = ones(m, 1); A = zeros(m, n); A(sub2ind(size(A),j,1:n)) = 1; x = A \ b; [dummy,p] = sort(rand(1,n)); y = A(:,p)\b; norm(x(p)-y) ```

It shows that unlike in Octave, mldivide in Matlab is not invariant with respect to column permutations. If there are multiple columns of the same norm, permuting columns of the matrix gets you different result than permuting the solution vector. This will surprise many users.

Since the mldivide (\) and mrdivide (/) operators are often part of a more complex expression, where there is no room to react to warnings or flags, it should prefer intelligence (robustness) to speed, and so the Octave developers are firmly of the opinion that Octave's approach for singular, under- and over-determined matrices is a better choice that Matlab's

• Octave extensions The extensions in Octave over MATLAB syntax are very useful, but might cause issues when sharing with MATLAB users. A list of the major extensions that should be avoided to be compatible with MATLAB are
• Comments in octave can be marked with ‘#’. This allows POSIX systems to have the first line as ‘#! octave -q’ and mark the script itself executable. MATLAB doesn't have this feature due to the absence of comments starting with ‘#’".
• Code blocks like if, for, while, etc can be terminated with block specific terminations like "endif". MATLAB doesn't have this and all blocks must be terminated with "end"
• Octave has a lisp like unwind_protect block that allows blocks of code that terminate in an error to ensure that the variables that are touched are restored. You can do something similar with `try`/`catch` combined with ‘rethrow (lasterror ())’ in MATLAB, however rethrow and lasterror are only available in Octave 2.9.10 and later.

Note that using `try`/`catch` combined with ‘rethrow (lasterror ())’ can not guarantee that global variables will be correctly reset, as it won't catch user interrupts with Ctrl-C. For example

 ``` global a a = 1; try _a = a; a = 2 while true end catch fprintf ('caught interrupt\n'); a = _a; rethrow (lasterror()); end ```

compared to

 ``` global a a = 1; unwind_protect _a = a; a = 2 while true end unwind_protect_cleanup fprintf ('caught interrupt\n'); a = _a; end ```

Typing Ctrl-C in the first case returns the user directly to the prompt, and the variable "a" is not reset to the saved value. In the second case the variable "a" is reset correctly. Therefore MATLAB gives no save way of temporarily changing global variables.

• Indexing can be applied to all objects in Octave and not just variable. Therefore `sin(x)(1:10);` for example is perfectly valid in Octave but not MATLAB. To do the same in MATLAB you must do `y = sin(x); y = y([1:10]);`
• Octave has the operators "++", "–", "-=", "+=", "*=", etc. As MATLAB doesn't, if you are sharing code these should be avoided.
• Character strings in Octave can be denoted with double or single quotes. There is a subtle difference between the two in that escaped characters like `\n` (newline), `\t` (tab), etc are interpreted in double quoted strings but not single quoted strings. This difference is important on Windows platforms where the "\" character is used in path names, and so single quoted strings should be used in paths. MATLAB doesn't have double quoted strings and so they should be avoided if the code will be transfered to a MATLAB user.

 [ < ] [ > ] [ << ] [ Up ] [ >> ] [Top] [Contents] [Index] [ ? ]
```© manpagez.com 2000-2021