Skip to content
LumenaryAcademy
Foundations 45 min

Getting started with MATLAB and Octave

Where the matrix laboratory came from, how MATLAB and GNU Octave relate, and your first scripts.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

A language where the matrix is the unit

Most programming languages treat a single number as the basic thing and make you build up collections with loops. Scientists and engineers, though, think in whole arrays: a signal is a vector of samples, an image is a matrix of pixels, a structure in an engineering model is a system of equations written as a matrix times a vector. MATLAB, short for matrix laboratory, turns that view into a language. Its basic value is a matrix, its operators work on whole arrays at once, and solving a system of linear equations is a single character.

That design makes MATLAB extremely productive for numerical work. Code reads close to the mathematics on the whiteboard: y = A * x + b means exactly what it says, for matrices of any size. Around the language, MathWorks built an environment with a desktop, plotting, a debugger and a large library of toolboxes for signal processing, control systems, optimisation, statistics, image processing and much more, plus Simulink, a graphical tool for modelling dynamic systems. MATLAB is taught in engineering faculties around the world and used daily in automotive and aerospace engineering, in research laboratories, in finance and in many industries that build physical things.

MATLAB is commercial software. GNU Octave is a free, open-source program whose language is largely compatible with MATLAB's: most scripts written for one run in the other unchanged. This course teaches the shared language through Octave, which anyone can install, and marks every place where the two differ, so that what you learn transfers directly to MATLAB if you use it at university or at work.

History & global context

From a teaching tool to an industry standard

In the 1970s, Cleve Moler, a numerical analyst then at the University of New Mexico, had helped write two celebrated Fortran libraries, LINPACK (for linear equations) and EISPACK (for eigenvalues). He wanted his students to be able to use them without learning Fortran, so in the late 1970s he wrote a small interactive program, also in Fortran, in which you could type matrix expressions and see the results. He called it MATLAB and gave it away to other universities.

An engineer named Jack Little saw the program and recognised its value for control engineering. With Steve Bangert, he rewrote MATLAB in C and added functions, graphics and the ability to write programs in files, and in 1984 Little, Moler and Bangert founded MathWorks to sell it. Toolboxes for specific fields soon followed, and in the early 1990s Simulink added block-diagram modelling of dynamic systems. MathWorks now releases MATLAB twice a year, named for the year and a letter (a spring "a" release and an autumn "b" release).

GNU Octave began around 1988 as companion software for a textbook on chemical reactor design by James Rawlings and John Ekerdt. John W. Eaton started full development in 1992, the first public alpha appeared in January 1993, and version 1.0 followed in 1994. The program is named after Octave Levenspiel, a chemical engineering professor of Eaton's, famous for quick back-of-the-envelope calculations. Octave is part of the GNU Project, is licensed under the GPL, and is developed by volunteers; it releases a new major version about once a year, and this course was checked with Octave 11. Octave's developers treat MATLAB compatibility as a goal and treat incompatibilities as bugs, though some newer MATLAB features and most toolboxes have no Octave equivalent.

DefinitionsH

Installing and running

Definition— Command window and workspace

Both MATLAB and Octave give you an interactive prompt (the command window, >> in both) where you type a statement and see the result at once. Every variable you create lives in the workspace until you clear it; who lists the variable names and whos adds their sizes and classes.

Definition— Script

A script is a plain text file ending in .m containing statements, run as if you had typed them at the prompt. You run hello.m by typing hello at the prompt (the file must be in the current folder or on the path, the list of folders searched for code), or from a terminal with octave hello.m.

Definition— Function file

A function file is an .m file that defines a function with the same name as the file, such as area.m defining area. Functions get their own lesson.

To install Octave, follow the instructions for your operating system at octave.org/download: there are installers for Windows, packages for Linux distributions, builds for macOS, and an official container image. Octave starts with a graphical desktop (editor, file browser, workspace view and command window), similar to MATLAB's. From a terminal you can also run it without the desktop:

bash
octave --version                 # check the installed version
octave --no-gui                  # an interactive prompt in the terminal
octave --no-gui hello.m          # run a script and exit

If you have MATLAB through a university or employer, everything in this course runs there as well, with the small differences noted along the way. MathWorks also provides MATLAB in the browser, MATLAB Online, with a MathWorks account.

Both systems have built-in help. help sum prints a function's documentation in the command window; doc sum opens the full reference page. Use them constantly: the documentation of both programs is thorough and full of examples.

Worked examplesH

Your first scripts

Printing

matlab
disp('Hello, world!')
disp('Habari, dunia! Hola, mundo! Merhaba, dünya!')
fprintf('%s has %d letters.\n', 'Octave', length('Octave'));
fprintf('pi is about %.4f, and e is about %.4f.\n', pi, exp(1));
text
Hello, world!
Habari, dunia! Hola, mundo! Merhaba, dünya!
Octave has 6 letters.
pi is about 3.1416, and e is about 2.7183.
  • disp(x) displays a value on its own line.
  • fprintf(format, values...) prints formatted text, using the same codes as C's printf: %s for text, %d for integers, %.4f for a number with four decimals, \n for a newline. It does not add a newline unless you ask for one.
  • Text in single quotes is a character array, the classic MATLAB text type. Use single quotes for text throughout this course: they mean the same thing in MATLAB and Octave. (Double quotes do not, as explained below.)
  • pi is a built-in constant and exp(1) is e. Parentheses call a function.

Automatic display and the semicolon

Leave the semicolon off the end of a statement and the result is displayed automatically:

matlab
radius = 2.5
area = pi * radius^2
circumference = 2 * pi * radius;
3 + 4
ans * 2
text
radius = 2.5000
area = 19.635
ans = 7
ans = 14
  • The semicolon suppresses the display. It is not required to end a statement, as it is in C or Java; it only means "do not show the result". Scripts usually end almost every line with one and print deliberately with disp or fprintf.
  • A value that is not assigned to anything goes into the special variable ans, which you can use in the next statement.
  • ^ is the power operator.

The layout of automatic display is one of the visible differences between the two programs. Octave prints radius = 2.5000 on one line; MATLAB prints the name, a blank line and the value indented on the next line. The values are the same. In this course, programs mostly print with fprintf and disp so the output is predictable in both.

Arrays everywhere

The next program converts a whole row of temperatures at once:

matlab
celsius = [-10 0 18.5 37 100];
fahrenheit = celsius * 9 / 5 + 32;

for k = 1:numel(celsius)
  fprintf('%6.1f C = %6.1f F\n', celsius(k), fahrenheit(k));
end

disp('The same table, printed by one fprintf call:')
fprintf('%6.1f C = %6.1f F\n', [celsius; fahrenheit]);
text
 -10.0 C =   14.0 F
   0.0 C =   32.0 F
  18.5 C =   65.3 F
  37.0 C =   98.6 F
 100.0 C =  212.0 F
The same table, printed by one fprintf call:
 -10.0 C =   14.0 F
   0.0 C =   32.0 F
  18.5 C =   65.3 F
  37.0 C =   98.6 F
 100.0 C =  212.0 F
  • [-10 0 18.5 37 100] is a row vector: square brackets, elements separated by spaces (or commas).
  • celsius * 9 / 5 + 32 applies the formula to every element at once. There is no loop: arithmetic between an array and a single number works element by element. This is vectorisation, and lesson 3 is all about it.
  • for k = 1:numel(celsius) loops over the positions 1, 2, …, 5. Indexing starts at 1, not 0, and uses parentheses: celsius(k).
  • The last line is a MATLAB idiom worth knowing. [celsius; fahrenheit] stacks the two rows into a 2-by-5 matrix (the semicolon inside brackets starts a new row). fprintf consumes the values of a matrix column by column and repeats its format until they run out, so each column, one temperature pair, becomes one line.

Everything is a matrix

Even values that look like single things are arrays with a size:

matlab
x = 42;
word = 'matrix';
row = [1 2 3];
col = [1; 2; 3];
nothing = [];
flag = x > 40;

fprintf('%-8s %-8s %s\n', 'name', 'class', 'size');
fprintf('%-8s %-8s %s\n', 'x', class(x), mat2str(size(x)));
fprintf('%-8s %-8s %s\n', 'word', class(word), mat2str(size(word)));
fprintf('%-8s %-8s %s\n', 'row', class(row), mat2str(size(row)));
fprintf('%-8s %-8s %s\n', 'col', class(col), mat2str(size(col)));
fprintf('%-8s %-8s %s\n', 'nothing', class(nothing), mat2str(size(nothing)));
fprintf('%-8s %-8s %s\n', 'flag', class(flag), mat2str(size(flag)));
text
name     class    size
x        double   [1 1]
word     char     [1 6]
row      double   [1 3]
col      double   [3 1]
nothing  double   [0 0]
flag     logical  [1 1]

A number is a 1-by-1 matrix of class double (a 64-bit floating-point number, the default numeric type; even 42 is stored as a double). A piece of text is a 1-by-6 matrix of characters. A comparison produces a logical value, true (1) or false (0). The empty matrix [] is 0-by-0. size always returns rows and columns, and mat2str turns a matrix into text you can print. Keeping track of sizes, and especially of rows versus columns, is most of the skill of writing correct MATLAB.

ExplanationH

Writing code that runs in both

Octave accepts everything in the common language, and also some extensions of its own that MATLAB rejects. Octave's documentation and many examples online use them, so you will meet them; recognise them and avoid them in code you want to share:

Octave-onlyPortable equivalent
# comment% comment
x != yx ~= y
x += 1, x++x = x + 1
printf(...)fprintf(...)
endif, endfor, endwhile, endfunctionend
"text with\tescapes" (a char array with escape sequences)sprintf('text with\tescapes')

The last row hides the most important difference. In Octave, double quotes make an ordinary character array in which backslash escapes such as \t are interpreted. In MATLAB (since 2017), double quotes create a string object, a different type with different behaviour, and backslashes are not escapes. Octave does not implement MATLAB's string type at all. So use single quotes for text, and sprintf or fprintf when you need escapes.

Other differences come from the libraries rather than the syntax. Some newer MATLAB functions are not yet implemented in Octave (for example contains and histcounts in Octave 11; Octave tells you so when you call them and points to a page explaining how to help); MATLAB's table and datetime types are missing; and toolboxes are MathWorks products, though Octave has community packages covering several of the same fields. Text is also stored differently: MATLAB characters are 16-bit Unicode code units, while Octave stores text as UTF-8 bytes, so in Octave length('dünya') is 6 (the ü takes two bytes) where MATLAB says 5. For plain ASCII text the two agree.

Under the hood, both programs interpret your code; MATLAB has had a just-in-time compiler for many years, which makes loops much faster than they once were, while Octave's interpreter is generally slower on loop-heavy code. Both hand the heavy numerical work (matrix products, solving equations, FFTs) to optimised libraries such as BLAS and LAPACK, the descendants of Moler's original Fortran, so vectorised code runs at similar, high speed in both.

Common misconceptionsH

Common misconceptions

Misconception

"Octave runs every MATLAB program." It runs most programs written in the core language, but not code that depends on toolboxes, Simulink, the string, table or datetime types, MATLAB's app-building tools, or functions Octave has not implemented yet. For teaching, numerical work and many research codes, it is an excellent free alternative; for a company built on Simulink, it is not a replacement.

Misconception

"The semicolon ends a statement, like in C." A line break already ends a statement. The semicolon only suppresses automatic display. A missing semicolon is not an error, just noise in the output (and, in a loop over a large array, a lot of noise).

Misconception

"Arrays start at 0, as in most languages." MATLAB and Octave index from 1, following mathematical notation for vectors and matrices. x(0) is an error.

Misconception

"42 is an integer." Numeric literals are double by default. Integer types such as int32 and uint8 exist, and you will meet them when reading images or binary files, but ordinary arithmetic is done in double precision.

Exercises

Exercises

Try anything you are unsure of at the Octave prompt, then compare your reasoning with the worked solutions.

1. Getting started with MATLAB and Octave

Warm-upHuman

What does the semicolon at the end of area = pi * r^2; do?

Choose one

2. Getting started with MATLAB and Octave

CoreComputational

What does this print?

x = [2 4 6];
fprintf('%d-', x * 10);
fprintf('\n');

3. Getting started with MATLAB and Octave

Warm-upComputational

What does disp(mat2str(size([1 2; 3 4; 5 6]))) print?

4. Getting started with MATLAB and Octave

Warm-upComputational

In Octave, what does the second line display?

a = 3;
a^2 + 1

5. Getting started with MATLAB and Octave

CoreComputational

How many lines does fprintf('%d %d\n', [1 2 3; 4 5 6]); print?

6. Getting started with MATLAB and Octave

CoreHuman

Which of these lines run unchanged in both Octave and MATLAB? Choose all that apply.

Choose all that apply

7. Getting started with MATLAB and Octave

StretchHuman

Why does this course write text in single quotes, such as 'hello', rather than "hello"?

Choose one

Further reading and resources