The basics
Files
MATLAB script files and function definition files use the extension .m. Script files are run by typing the file name (sans extension) into the command window like a regular function call; likewise, function calls are resolved by looking for a file with that name in the working directory. This has the unfortunate consequence that the names of script and function files must also be valid identifiers (regex [A-Za-z][_0-9A-Za-z]*).
MATLAB script and function files can be encrypted with a proprietary algorithm tightly guarded by MathWorks and their prodigious legal team. These files work identically to standard script and function files, but are not human-readable. They use the extension .p.
Workspaces and scripts
The workspace is the collection of user-defined variables in the global scope. Unlike in most programming languages, the contents of the workspace persists across executions, meaning that scripts are not necessarily idempotent. In fact, MATLAB provides a mechanism for saving the workspace to disk as a .mat file to be loaded back in later. Think of the workspace as more of a persistent scratchpad for working out problems, and not as something ephemeral.
Likewise, scripts are a bit different to regular programs. MATLAB feels more like a REPL than a proper autonomous runtime, and scripts are just lists of code that MATLAB will diligently paste into the command window one at a time and then run.
Noisy output
MATLAB is noisy by default — any expression or assignment that is not terminated by a ; will be printed to the command window in full. This is because MATLAB is a calculator first, and a programming language second. It’s a programmable calculator, really.
Note that semicolons can also be used in place of newlines anywhere in the program; the two characters are interchangeable.
Command syntax
Command syntax is an alternate function calling syntax for functions that have either no arguments or only string-type arguments. Just omit the parentheses and quotation marks.
clear % equiv. to clear() help uint8 % equiv. to help("uint8")
Built-in help
The help function will print the documentation for a given function to the command window. This is quicker when combined with command syntax.
help("sin") help sin
Language elements
Quick scraps
Logical negation is performed with the ~ operator.
1 ~= 2 % true ~5 % 0
Arrays can be destructured into variables.
[a b] = 1:2 %a=1, b=2
Comments
Comments are denoted with a leading %, and continue to the end of the line.
Section comments denote the start of a block of code. The MATLAB IDE allows code to be executed one section at a time.
%% This is a section header. % This is a comment. %{ This is a multiline comment. %} a = 1; % This is also a comment.
Numeric types
The default numeric type is a double-precision float, called double. Single-precision floats are called single. There are also fixed-width integer types int8, int16, int32, int64, and all of their uint equivalents. Finally, there is a boolean type logical, which can be either 0 or 1 and can be used interchangeably with other numeric types in math operations. All numbers saturate at bounds.
Values can be converted between types by using the type name as a function, like uint8(my_num). Use class(value) to see the type of a value.
String types
A string scalar is created by wrapping text in " delimiters. A string array is an array of string scalars. Strings are treated as atomic values, not as arrays of characters. Calling double("123") will parse the string as an integer, rather than treating each character in the string individually.
A character array is created by wrapping text in ' delimiters. It is analogous to an array of integers, where each element of the array is the Unicode scalar value of the corresponding character (limited to the basic multilingual plane). Characters are presumably stored as uint16 values internally. Calling char([65 66 67]) will return the character array 'ABC', calling double('ABC') will perform the inverse.
"a string scalar" 'a character array'
Matrices and arrays
Matrices are MATLAB’s bread and butter, working similarly to multidimensional arrays in APL. The MATLAB documentation refers to one-dimensional arrays as arrays, and to multi-dimenional arrays as matrices. Additionally, horizontal arrays are also called ‘row vectors’ and vertical arrays ‘column vectors’.
A matrix literal syntax can be used to create arbitrary arrays or matrices by wrapping lists of values with [] brackets. Spaces and commas delimit columns, newlines and semicolons delimit rows.
row = [1, 2, 3]; column = [1; 2; 3]; matrix = [ 1 2 3 4 5 6 7 8 9 ];
The colon operator will generate a row vector with syntax identical to Python’s range function. The syntax is either start:stop or start:step:stop, with end value included if it is not stepped over. The transposition operator ' (high precedence) can be used to generate a column vector instead.
1:3 % [1 2 3] 1:2:6 % [1 3 5] 5:-1:3 % [5 4 3] (1:3)' % [1;2;3]
The linspace(start,stop,step) function will generate a row vector with a fixed number of elements, linearly interpolating between a start and stop value. Use this when a specific array length is required. The step value is 100 if not provided.
linspace(1,5,3) % [1 3 5] linspace(5,1,3) % [5 3 1] linspace(1,5,3)' % [1;3;5]
Matrices can be sliced and the slices mutated. Indexing with one dimension will treat the array or matrix as a flat list, travelling down each column from top-to-bottom. Indexing with two dimensions is done by row and then by column.
Indexing with a vector of numbers will select all elements whose indices are in that vector, with : selecting all elements. Indexing with a vector of booleans will mask the elements, returning all elements for which the mask is true.
M = [ 1 2 3 4 5 6 7 8 9 ]; [T F] = [true false] % One dimensional M(2) % 4 M(7) % 3 M(2:3) % [4 7] M([T F T T]) % [1 7 2] M(M>5) % [7 8 6 9] % Two dimensional M(2, 3) % 6 M(2:3, 1) % [4; 7] M(2:3, 1:2) % [4 5; 7 8] M(:, 2:3) % [2 3; 5 6; 8 9] M(:, [F T T]) % [2 3; 5 6; 8 9]
Arrays and matrices can be concatenated left-to-right with [] brackets.
a = [1 2 3] b = [4 5 6] [a b] % [1 2 3 4 5 6]
Arrays and matrices can be added element-wise with the + operator. Multiplication and exponentation perform matrix-specific operations, so prefix operators with a . to perform the operation element-wise.
a = [1 2 3] M = [ 1 2 3 4 5 6 7 8 9 ]; a + 1 % [2 3 4] a + a % [2 4 6] M + a % [2 4 6 % 5 7 9 % 8 10 12] a .* a % [1 4 9]
Loops and conditionals
While loops:
i = 1 while i<=5 disp(i) end
For loops:
for i=1:5 disp(i) end
If statements:
if i>0 disp("positive") elseif i<0 disp("negative") else disp("zero") end
Switch statements:
switch i case 0: disp("No real roots") case 1: disp("One real root") case 2: disp("Two real roots") end
Linear equations
To solve the following system of linear equations:
a = [1 2; 2 -1]; b = [4; 3]; x = a\b; % [2; 1]