MATLAB Octave CLI
Internal
Overview
';' after a statement suppressed the default output to stdout.
Comments
% this is a comment
Prompt
PS1('>> ')
Search Path
addpath('<directory-name>')
Script Execution
Scripts from the current directory are executing by specifying the name of the script (without the .m extension). To update the current directory use cd.
In-Line Operations
1 + 2 2 - 1 1 * 2, 2 * C % where C is a matrix 2 / 1 2 ^ 6
Logical operations
Equality:
1 == 2
Non-equality:
1 ~= 2
Logical AND:
1 && 0
Logical OR:
1 || 0
Variable Assignment
Also see:
Scalar Variable Assignment
<scalar-variable-name> = <variable-value>
Vector Variable Assignment
Vector indices are 1-based.
Assignment and literal initialization:
<vector-variable-name> = [ v1 v2 v3 ... ] % An (1, n) vector <vector-variable-name> = [ v1; v2; v3; ... ] % An (n, 1) vector
Other Types of Vector Initialization
Start from "start-value" (inclusively), increment with "increment-step" until the value is strictly larger than "end-value":
v = <start-value>:<increment-step>:<end-value>
Start from "start-value" to "end:value" with increments of 1:
v = <start-value>:<end-value>
v = zeros(1, 3) v = zeros(3, 1) v = ones(1, 3) v = ones(3, 1)
Matrix Variable Assignment
Matrix indices are 1-based.
Assignment and literal initialization:
<two-dimensional-matrix-variable-name> = [ v11 v12 ... v1n; v21 v22 ... v2n; ...; vm1 vm2 ... vmn ] % A (m, n) matrix.
Example:
A = [1 2; 3 4]
Commas between row elements are accepted and ignored:
A = [1, 2; 3, 4]
Other Types of Matrix Initialization
C = zeros(2, 3) C = ones(2, 3)
Concatenation
A = ... B = ... C = [A B] % same as [A, B] C = [A; B]
Data Selection
Indexing
An element of a matrix:
<Matrix-var-name>(<1-based-row-number><1-based-column-number>)
A(2, 3)
Subset Indexing
These indexing mechanism can be used to access data, but also to assign data in the original variable, by specifying the selection expression at the left of the assignment.
Vector Indexing
Subset of a vector:
v(<first-index>:<last-index>)
Matrix Indexing
Everything in a second row of a matrix:
A(2, :)
Everything from the first and the third row:
A([1 3], :)
Everything in the second column:
A(:, 2)
Everything in the first and the second column:
A(:, [1, 2])
All Elements of Matrix in a Single Column Vector
A(:)
Variable Management
who
Shows the name of the variable in the work space.
whos
Details about variables in the work space.
clear
Delete the names matching the pattern from the symbol table. The pattern is a simplified regular expression, with '?', '*', '[...]'. With no arguments, all user-define variables (local and global) are deleted.
Initialization Functions
zeros
v = zeros(1, 3) C = zeros(2, 3)
ones
v = ones(1, 3) C = ones(2, 3)
eye
Returns an identity matrix. When invoked with a single scalar argument n, it returns a square n x n identity matrix.
C = eye(3)
rand
v = rand(1, 3) C = rand(2, 3)
randn
Gaussian.
v = randn(1, 3) C = randn(2, 3)
Data Size
size
size()
Dimensions of a matrix:
size(A)
Returns a vector with two elements (number of rows and number of columns).
Number of rows of a matrix:
size(A, 1)
Number of columns of a matrix:
size(A, 2)
length
Should only be applied to vectors, for matrices is confusing.
Element-Wise Operations
Element-wise multiplication
A .* B
Element-wise comparison:
A < 3
Other element-wise operations:
A .^ 2
1 ./ A
Transpose
A'
Inverse
inv(A)
Pseudo-inverse:
pinv(A)
Data Loading and Saving
load
Load the named variables from the file. If no variables are named, all variables found in the file will be loaded. Note that the file is in ASCII format, no variable names are saved in the file, so the variable that will be created will be named after the file (the basename of the file name).
load <file-name>
load('<file-name>')
data = load('<file-name>')
save
save <file-name.mat> <variable-name>
Saves the data in a MATLAB format, and the variable name is also saved in the file.
To save the data as ASCII (the name of the variable is not saved in the file):
save <file-name.txt> <variable-name> -ascii
Display
By default, the runtime displays 5 significant digits in human readable format (format short for scalars and format loose for matrices).
To print the value of the variable, simply type the name of the variable:
<variable-name>
disp
disp(<variable-name>)
Also see format.
printf
printf fprintf sprintf
a = pi; sprintf('this is pi with 6 decimals %0.6f', a);
fprintf() is like printf(), just that the output is written to the FID stream instead of stdout.
Also see:
format
Reset or specify the format of the output produced by disp and the normal output mechanism.
Also see:
short
Fixed point format with 5 significant figures in a field that is a maximum of 10 characters wide.
long
loose
Control Elements
Loops
For all loops, 'break' and 'continue' work:
for
for i = <range> <statement> end;
for i = 1:10 disp(i) end;
The range can be a vector:
v = [2 4 6 8] for i = v disp(i) end;
while
i = 1; while i <= 5; i = i + 1; end;
if
if <condition> <statement> endif;
if <condition> <statement> else <statement> endif;
if <condition> <statement> elseif <condition> <statement> ... else <statement> endif;
Functions
Create a file with a .m extension and a content similar to:
function [return-variables =] <function-name>([comma-separated arguments]) <body> end
The "return-variables" section of the function header defines which variables represent the return values of the function. A function may return zero, one or more values.
A function that does not return a value:
function somefunc(...)
A function that returns one value:
function result = somefunc(...)
A function that returns multiple values:
function [result1, result2] = somefunc(...)
A function may have zero, one or more arguments. The () must be specified even if there are no arguments.
The function body uses the arguments and assigns values to the return variables defined in the function header.
Function References
Input
fprintf('Program paused. Press enter to continue.\n'); pause;
Filesystem
cd
Modify the current directory.
pwd
Print working directory.
Miscellaneous
clc
Clears the terminal screen and move the cursor to the upper left corner.
log
abs
max
max(A) does column-wise maximum for a matrix.
max(A, [], 1) max(A, [], 2)
Maximum for the entire matrix:
max(max(A))
Equivalent with
max(A(:))
find
sum
Fun of all elements along the specified dimension.
For a vector sums all elements.
For a matrix, sums columns and presents the result as a horizontal vector.
prod
floor
ceil
flipud
Plotting
figure
Opens a new (empty) figure window. It can be closed with close.
plot
Displays a 2D plot.qq
plot(x, y, 'rx', 'markersize', 10);
Format arguments:
- marker color ('r', 'g', 'b', ...)
- maker style ('x', 'o', ....)
Other format properties:
- 'linestyle'
- 'linewidth',
- 'color',
- 'marker'
- 'markersize'
- 'markeredgecolor'
- 'markerfacecolor'
xlabel
Sets the X axis label.
ylabel
Sets the Y axis label.
close
Close figure windows.
Recipes
Average value for a vector: