MATLAB vs Octave
GNU Octave is a free, open-source program whose language is largely compatible with MATLAB. Most everyday code (matrices, indexing, loops, functions, plotting, file I/O, linear algebra) runs unchanged in both, which is why every runnable example in this course is checked in Octave. But they are separate implementations, and the differences matter when you share code or move between them. This lesson is a practical guide to those differences, as of MATLAB R2025b/R2026a and Octave 11.
| MATLAB | GNU Octave | |
|---|---|---|
| Licence | Commercial (free trials, campus and home licences) | Free software (GPL) |
| Made by | MathWorks | Volunteer community |
| Desktop | MATLAB Desktop, Live Editor, App Designer | Qt GUI with editor, debugger, file browser, workspace |
| Add-ons | Toolboxes (paid) + File Exchange | Packages (pkg install -forge ...), free |
| Speed of loops | JIT compiler: loops are fast | Interpreter only: loops are much slower, vectorise |
| Block diagrams | Simulink | none |
| Online | MATLAB Online | Octave Online (third party) |
Code that runs in both
The common language is large. Everything below is standard MATLAB and also valid Octave:
A = magic(4);
evens = A(mod(A, 2) == 0)'; % logical indexing
colMeans = mean(A); % column-wise functions
centred = A - colMeans; % implicit expansion (R2016b+)
words = {'delta', 'alpha', 'charlie'};
lens = cellfun(@numel, words); % cellfun
s = struct('name', {'Ann', 'Bo'}, 'age', {31, 27});
tok = regexp('x=12, y=7', '(\w)=(\d+)', 'tokens');
m = containers.Map({'a', 'b'}, {1, 2});
fprintf('evens: %s\n', mat2str(evens));
fprintf('row 1 centred: %s\n', mat2str(centred(1, :)));
fprintf('sorted: %s, lengths %s\n', strjoin(sort(words), ' '), mat2str(lens));
fprintf('oldest: %s\n', s([s.age] == max([s.age])).name);
fprintf('%s is %s\n', tok{2}{:});
fprintf('map has %d keys, b -> %d\n', m.Count, m('b'));evens: [16 4 2 14 10 6 8 12]
row 1 centred: [7.5 -6.5 -5.5 4.5]
sorted: alpha charlie delta, lengths [5 5 7]
oldest: Ann
y is 7
map has 2 keys, b -> 2
If you stick to this common subset, and test in both, your code is portable. The rest of the lesson is about where the subset ends.
1. Octave accepts extra syntax that MATLAB rejects
Octave is more permissive. These forms work in Octave but are syntax errors in MATLAB, so avoid them in shared code (this course never uses them):
# a hash comment % MATLAB: use %
if x != 3, printf("%d\n", x); endif % MATLAB: ~=, fprintf, end
x += 2; x *= 3; n++; % MATLAB: x = x + 2; x = x * 3; n = n + 1;
do
n--;
until n < 5 % MATLAB: while loop
y = magic(3)(2, 2); % index a call result directly; MATLAB: M = magic(3); y = M(2, 2);
unwind_protect % MATLAB: try/catch or onCleanup
risky();
unwind_protect_cleanup
disp('always runs');
end_unwind_protect
function r = f(x)
r = 2 * x;
endfunction % MATLAB: endOctave also has printf, puts, fdisp and ifelse/merge that MATLAB lacks; fprintf and disp work in both. (Older Octave also accepted ** for powers; Octave 11 no longer does.)
2. MATLAB features Octave doesn't have (yet)
The other direction is bigger. These MATLAB features are missing in Octave 11, so the course shows them in non-run blocks with MATLAB's output, next to a portable alternative:
| MATLAB feature | Lesson | Portable alternative |
|---|---|---|
string arrays ("text" as a string object) |
String Arrays | char arrays and cell arrays of char |
contains, startsWith, replace, strip, extractBetween... |
String Functions | strfind, strncmp, strrep, strtrim, regexp |
table, readtable, groupsummary |
Tables | struct of column vectors, accumarray |
datetime, duration |
Dates & Times | datenum, datestr, datevec |
categorical |
Categorical Data | unique + integer codes |
arguments validation blocks |
Input Validation | validateattributes, inputParser |
histcounts, histogram, fillmissing, rmmissing |
Statistics Functions | hist, histc, accumarray, isnan |
readmatrix, writematrix, readcell |
CSV & Delimited Files | dlmread, dlmwrite, csvread, textscan |
classdef enumeration, events/addlistener, property validation |
Handle Classes & Events | constants in a class, callbacks stored in properties |
| Live Editor, App Designer, Simulink | Live Scripts & Apps | %% + publish, uicontrol, ODE code |
matlab.unittest framework |
Unit Testing | function-based tests, Octave's %!test blocks |
Octave's classdef support covers the basics well (properties, methods, constructors, handle classes, inheritance, Dependent properties with get. methods) but in Octave 11 an enumeration block is a syntax error, addlistener fails, and a property declared as n (1,1) double only prints a warning that the size and class are not checked.
3. The same code, different behaviour
These are the subtle ones, because nothing fails: the code runs in both and does something different.
Double-quoted text
In MATLAB, "a\tb" is a string object and backslash sequences are not interpreted. In Octave, "a\tb" is a char array and \t becomes a tab:
s = "a\tb";
class(s)
disp(s)MATLAB output:
ans =
'string'
a\tbOctave output:
ans = char
a bFor portable code use single quotes, and let sprintf/fprintf (which interpret escapes in both) produce special characters:
s = sprintf('a\tb');
fprintf('class %s, %d characters, char codes %s\n', class(s), numel(s), mat2str(double(s)));class char, 3 characters, char codes [97 9 98]
Display layout
Values shown without a semicolon look different. Octave's layout is more compact, which is what the saved outputs on this site show:
x = 5
e = []
p.b = 3x = 5
e = [](0x0)
p =
scalar structure containing the fields:
b = 3
MATLAB output (default format loose):
x =
5
e =
[]
p =
struct with fields:
b: 3
Don't parse displayed values; print what you need with fprintf, and the output is identical in both.
Error messages and identifiers
Both throw errors for the same mistakes, but the wording and the identifiers differ:
try, undefinedThing + 1, catch err, fprintf('%s\n %s\n', err.identifier, err.message), end
try, m = magic(3); m(5, 1), catch err, fprintf('%s\n %s\n', err.identifier, err.message), end
try, [1 2] * [3 4], catch err, fprintf('%s\n %s\n', err.identifier, err.message), endOctave:undefined-function
'undefinedThing' undefined near line 1, column 6
Octave:index-out-of-bounds
m(5,_): out of bound 3 (dimensions are 3x3)
Octave:nonconformant-args
operator *: nonconformant arguments (op1 is 1x2, op2 is 1x2)
MATLAB output:
MATLAB:UndefinedFunction
Unrecognized function or variable 'undefinedThing'.
MATLAB:badsubscript
Index in position 1 exceeds array bounds. Index must not exceed 3.
MATLAB:innerdim
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To operate on each element of the matrix individually, use TIMES (.*) for elementwise multiplication.So tests that compare built-in error messages are not portable. Errors that you raise with error('myapp:badInput', ...) keep your identifier and message in both programs; check those.
Default MAT-file format
save('data.mat', 'x') writes a binary MAT-file in MATLAB, but Octave's default format is its own text format, which MATLAB cannot load. Ask for the MATLAB format explicitly with -v7 (or -v6, or -mat):
x = magic(3);
save('octave_default.mat', 'x');
save('-v7', 'portable.mat', 'x');
for f = {'octave_default.mat', 'portable.mat'}
fid = fopen(f{1}); header = fgetl(fid); fclose(fid);
fprintf('%-19s starts with "%s"\n', f{1}, header(1:10));
endoctave_default.mat starts with "# Created "
portable.mat starts with "MATLAB 5.0"
Loading works in both directions once the file is a real MAT-file: load('portable.mat') restores x in MATLAB and Octave. See MAT-Files: save & load.
Functions inside scripts
MATLAB (R2016b+) allows local functions in a script, but only at the end of the file. Octave runs a script line by line, so a function must be defined before the line that calls it; that is the opposite order. Portable options: put each function in its own .m file (works everywhere), or use MATLAB's order and run the script in Octave with the definitions moved to the top behind a 1; line (this site does exactly that when it verifies examples).
Smaller differences
| Topic | MATLAB | Octave |
|---|---|---|
Speed of for loops |
Fast (JIT) | Slow: vectorise (Vectorization) |
| Random numbers with the same seed | One sequence | A different sequence (don't compare printed random values) |
| Default plot look | MATLAB colours and fonts | Similar colour order, different fonts and toolkit (Qt/OpenGL or gnuplot) |
inputname, evalin, assignin |
Supported | Supported, with small differences |
| Startup file | startup.m |
~/.octaverc |
| Run a script from a shell | matlab -batch "myscript" |
octave --no-gui myscript.m or octave --eval "..." |
| Help text | help, doc (HTML) |
help, doc (Texinfo) |
Writing portable code
- Use the common subset:
%comments,~=,end,fprintf, single-quoted char arrays. - Avoid MATLAB-only types (
string,table,datetime) unless you only target MATLAB. - Save MAT-files with
-v7; prefer CSV/text for data exchange. - Raise errors with your own identifiers and test those, not built-in messages.
- When behaviour must differ, branch on the environment:
isOctave = exist('OCTAVE_VERSION', 'builtin') ~= 0;
if isOctave
fprintf('Running in GNU Octave\n');
else
fprintf('Running in MATLAB %s\n', version('-release'));
endRunning in GNU Octave
OCTAVE_VERSION is a built-in function only in Octave, so exist returns 5 there and 0 in MATLAB. Test in both programs before you publish code.
Learn more: Toolboxes, MATLAB vs Python, Error Handling.
Test yourself
Which line runs in Octave but is a syntax error in MATLAB?
if x ~= 3, disp(x), endx += 1;fprintf('%d\n', x)y = x(end);
What does "a\tb" contain in MATLAB?
- A char array with a tab
- A string with the four characters a, \, t, b
- An error
- A cell array
Why should Octave users write save('-v7', 'data.mat', 'x') when sharing with MATLAB users?
- -v7 compresses better
- Octave's default save format is a text format MATLAB can't load
- MATLAB requires the option to read any file
- It is faster