MATLAB Octave CLI

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

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.

Multi-Line Statements

A long statement may be broken into multiple lines by specifying "..." at the end of the line(s).

Subjects

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:

Variables

Scalar Variable Assignment

<scalar-variable-name> = <variable-value>

Vector Variable Assignment

Vector indices are 1-based.

Vector

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

Horizontal 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>

Vector Initialization Functions

v = zeros(1, 3)
v = zeros(3, 1)
v = ones(1, 3)
v = ones(3, 1)

Matrix Variable Assignment

Matrix indices are 1-based.

Matrix

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 = ...

Concatenation on the horizontal direction. For this to work, A's number of rows must be equal with B's number of rows, otherwise we get a "horizontal dimensions mismatch" error:

C = [A B] % same as [A, B]

Concatenation on the vertical direction. For this to work, A's number of columns must be equal with B's number of columns:

C = [A; B]

Data Size

size

Return the size of the variable given as argument. The result is always a vector with two elements, on the first position in vector is the number of rows, and on the second position is the number of columns.

For a scalar, the result is [1 1].

For a vector, the result is either [length 1], if the vector is vertical, or [1, length] if the vector is horizontal.

size(var-name)

To further qualify, the number of rows (the first dimension) can be obtained with:

size(A, 1)

and the number of columns (the second dimension) with:

size(A, 2)

length

Return the length of the argument. The length is 0 for empty objects, 1 for scalars, the number of element for vectors, and the number of rows or columns, whichever is greater, for matrices. The only reasonably useful use case is to use it for vector only, when it is convenient to use it in-line - it returns a value, unlike size, which returns a matrix. length() should only be applied to vectors, for matrices is confusing.

numel

Return the number of elements in the object A. Optionally, if indices i1, i2, ... are supplied, return the number of elements that would result from indexing with the given indices.

numel(A)

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 from the first, second and third row:

A(1:3, :)

Note that the first argument may be a vector containing specific indices, as the one returned by the find function.

Everything in the second column:

A(:, 2)

Everything in the first and the second column:

A(:, [1, 2])

Note that the second argument may be a vector containing specific indices, as the one returned by the find function.

Special Indexes

"end" can be used as follows:

v(2:end)

All Elements of Matrix in a Single Column Vector

A(:)

The inverse transformation is with reshape().

This is how these two are used together. If we have a A mxn matrix:

a11 a12 ... a1n 
...
am1 am2 ... amn

then A(:) results in a column vector with m X n elements, build by concatenating first column, second column, etc:

a11
a21
...
am1
a12
a22
...
am2
...
a1n
...
amn

To reconstruct the initial matrix, use reshape(v, m, n).

Multiple matrices can be concatenated like this:

v = [M1(:); M2(:); ... Mx(:)]

In order to recover the original matrices, we can use:

reshape(section-in-the-column-vector, desired-matrix-m, desired-matrix-n)

reshape(v(100:200), m, n)

For example, if M1 is 10x11, M2 is 10x11 and M3 is 1x11, we can recover M1, M2 and M3 from [M1(:); M2(:); M3(:)] as follows:

M1 = reshape(v(1:110), 10, 11)
M2 = reshape(v(111:220), 10, 11)
M3 = reshape(v(221:231), 1, 11)

find

By default, the function returns a vector of indices of nonzero elements of a matrix.

The "find" condition can be specified between parentheses. The following example returns a vector filed with indices of y elements that are zero.

find(y == 0)

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

For allocation and initialization of a new structure of the same type as the argument, use one of the initialization functions applied to size(source). size preserves the dimensionality. For an example see zeros().

zeros

v = zeros(1, 3)
C = zeros(2, 3)

Initialization with zero of a new structure of the same type as the argument. It works with scalars, vectors and matrices.

n = zeros(size(i))

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)

Element-Wise Operations

Element-wise multiplication

A .* B

Element-wise comparison:

A < 3

Element-wise addition:

A .+ 1

Element-wise multiplication:

2 .* A

Element-wise division:

1 ./ A

Element-wise exponential:

A .^ 2

Element-wise e exponential:

e .^ A

Logical equality:

v == 3

Returns a new vector the size of v, initialized to 0 or 1, where elements with the indices of the v elements equals to 3 are 1.

not

not(y)

log

abs

floor

ceil

round

Vector-Wise Operations

max

max(A) does column-wise maximum for a matrix, as a row vector. The default form is equivalent with:

max(A, [], 1) 

which signifies: calculate maximum by iterating over dimension 1 - which results in maximum per column.

To calculate the maximum per row (iterate over dimension 2) use:

max(A, [], 2)

This returns the maximum per row as a column vector.

Maximum for the entire matrix:

max(max(A)) 

Equivalent with

max(A(:))

If called with two output arguments, max() also returns the first index of the maximum value.

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.

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.

sprintf() does not send anything to stdout, it just returns a formatted string, which would have to be displayed with disp().

Also see:

Generic printf

format

Reset or specify the format of the output produced by disp and the normal output mechanism.

Also see:

Display

short

Fixed point format with 5 significant figures in a field that is a maximum of 10 characters wide.

long

loose

Input

fprintf('Program paused. Press enter to continue.\n');
pause;

Filesystem

cd

Modify the current directory.

pwd

Print working directory.

Plotting

figure

Opens a new (empty) figure window. It can be closed with close.

plot

Displays a 2D plot. Several invocation styles are available, as shown below. If no format and no property/value pairs are specified, then the default plot style is solid lines with no markers and the color determined by the "colororder" property of the current axes. format and property/value pairs can be combined in the same invocation.

Display y Values Evenly Spaced

If a single data argument is supplied, it is taken as the set of Y coordinates and the X coordinates are assumed to be the indices of the elements.

plot(y[, property, value, ...])

This is equivalent with:

plot(1:numel(y), y)

For more details on property/value pairs, see property/value pairs below.

Display x,y Pairs

If both arguments are vectors, the elements of y are plotted versus the elements of x.

plot(x, y)
plot(x, y[, property, value, ...])
plot(x, y[, format])

Example:

plot(x, y, 'rx', 'markersize', 10);

For more details on property/value pairs, see property/value pairs below.

Other Special Cases

  • If x and y are scalars, a single point is displayed.
  • If x is a vector, and Y is a matrix, then the column or rows of Y are plotted versus x, using whichever combination matches, with columns tried first.
  • If X is a matrix and the only argument, it is equivalent with superimposing plot(X(:,1)), plot(X(:,2)), ...
  • If X is a matrix and y is a vector, y is plotted versus the column or rows of X, using whichever combination matches, with columns tried first.
  • If both arguments are matrices, the columns of Y are plotted versus the columns of X - both matrices must have the same number of rows and columns.

Property/Value Pairs

Multiple property/value pairs may be specified, but they must appear in pairs.

Properties:

linestyle

'-' solid lines
'--' dashed lines
':' dotted lines
'-.' dash-dotted lines

linewidth

color

'k' black
'r' red
'g' green
'b' blue
'm' magenta
'c' cyan
'w' white
'y' yellow

marker

markerstyle

plot(..., 'markerstyle', '+', ...) 

does not seem to work, specify '+' directly as format.

'+'  crosshair
'o'  circle
'*'  star
'.'  point
'x'  cross
's'  square
'd'  diamond
'^'  upward-facing triangle
'v'  downward-facing triangle
'>'  right-facing triangle
'<'  left-facing triangle
'p'  pentagram
'h'  hexagram

markersize

An integer.

markeredgecolor

See color.

markerfacecolor

See color.

Format

The "format" argument is composed of three parts: linestyle, makerstyle, color. When markerstyle is specified, but no linestyle, only the markers are plotted. Similarly, if a linestyle is specified, but no markerstyle, then only lines are drawn. If both are specified then lines and markers will be plotted.

Format arguments:

  • marker color ('r', 'g', 'b', ...)
  • maker style ('x', 'o', ....)

xlabel

Sets the X axis label.

ylabel

Sets the Y axis label.

close

Close figure windows.

Recipes

Recipes

String Functions

String Functions

Miscellaneous

clc

Clears the terminal screen and move the cursor to the upper left corner.

prod

flipud

squeeze

fminunc

fminunc() is an optimization solver that finds the minimum of an unconstrained function.

fmincg

Minimize a continuous differentialble multivariate function.

exp

Exponential:

exp(x)