Matlab in a Nutshell
Matlab syntax in a nutshell:
Status: 03.10.2014
pdf version: Syntax_Matlab.pdf
word version: Syntax_Matlab.docx
html version:
Here is a short Matlab command overview for the following topics:
Variables:
Variable names consist of letters, numbers and underscores. They always begin with a letter. A distinction is made between upper and lower case letters.
a=7 | Generates a variable a with the value 7, or changes the value of the variable a to 7 if a is already a known variable. In Matlab, a single equals sign denotes a definition, "a set equal to 7". |
clear a | Deletes the variable a from the current workspace (the command line or a function). |
clear all | Deletes all variables in the current workspace. |
Vectors:
v=[1 4 78] | Generates a line vector v with three components (the components within a row can be separated either by spaces or commas). Square brackets generally enclose the related components of a vector or matrix. |
v=[1; 4; 78; 15.8; 0] | Generates a column vector v with five components (rows are separated by semicolons). |
l=[] | Generates an empty vector l. |
count=1:10 | Generates a vector zaehl with 10 components, which are assigned values from 1 to 10. |
back=10:-2:1 | Generates a vector with 5 components that counts backwards from 10 to 1 in steps of two. |
new=[count back] | Generates a vector with 15 components by assigning the vectors count and back are concatenated to form a long vector. |
l=linspace(a,b,n) | Generates a vector l with n components, each with the same distance between a and b lie. |
l=linspace(a,b) | Generates a vector with 100 components between a and b. |
b=v(2) | Generates a variable bwhich is the value of the second component of v is assigned. |
v(2) | Assigns the standard variable ans the value of the second component of v . |
c=v(1:3) | Generates a vector c with three components to which the first three values of v are assigned. |
d=v(end) | Generates a variable dto which the last value of the vector v is assigned. |
all=v(:) | Equates the variable all with vector v. Other notations are all=v or all=v(1:end). |
line=v' | Transposed v: generates a row vector rowto which all values of the column vector v are assigned. (Works the same for column by row). |
l=length(v) | Assigns the variable l the number of components of v . |
Matrices:
m=[1 5; 79 0.5; 17 0] | Generates a matrix with three rows and two columns (rows are separated by semicolons, the values within a row by spaces or commas). |
z=zeros(3,4) | Generates a matrix with three rows and four columns whose values are all 0. |
o=ones(3,4) | Similarly, but all values are 1. |
e=m(2,1) | Assigns the value of the second row and first column of m to the variable e. |
e=m(2) | Also assigns the value of the second row and first column to the variable e. Linear indexing counts along the columns. (e=m(4) would be the value of the first row and second column in this example). |
row1=m(1,:) | Creates a vector row1 with all values of the first row of m. |
[rows,columns]=size(m) | Assigns the number of rows to the variable rows and the number of columns to the variable columns in matrix m . |
rows=size(m,1) | Assigns the size of the first dimension, i.e. the number of rows, to the variable rows. Correspondingly for the other dimensions of a matrix (columns=size(m,2) depth=size(m,3) etc) |
l=length(m(:)) | Assigns the variable l the number of all elements of the matrix m to the variable l. |
mt=m' | Transposes the matrix m. The first row of m becomes the first column of mtetc. |
B = repmat(A,m,n) | Replicates the matrix A. B is a matrix in which A m-times "among themselves" and n-times "next to each other". |
B = reshape(A,m,n) | Sorts the entries of matrix A into those from m rows and n columns into the matrix B. (numbered column by column) |
Operators
Arithmetic operators
+, - *, /, ^ | Apply arithmetic operation to whole matrix or whole vector |
.*, ./ , .^ | Calculate arithmetic operation point by point for each element |
Comparison operators
<, >, <=, >=, == | Return truth values, 1 for true, 0 for false. == is the test for equality (in contrast to =which means "set equal"). |
a=(2<3); | For vectors and matrices, the comparison is made pointwise |
l=isequal(a,b) | Assigns the variable l assigns the truth value for the test for equality of a and b to the variable l. a and b do not have to be numbers, vectors or matrices, isequal works for all data types (e.g. also strings and structures). |
Logical operators:
Point-by-point comparison that returns truth values.
& | logical and |
| | logical Or |
xor() | logical either-or |
~ | logical negation |
Mathematical functions
a=abs(m) | Absolute value, calculated component by component from matrix m |
a=sqrt(m) | Square root, calculated component by component from matrix m. |
a=exp(m) | Exponential function, calculated component by component from matrix m. |
a=log(m) | Natural logarithm, calculated component by component from matrix m. |
a=log10(m) | Logarithm to base 10, calculated component-wise from matrix m. |
a=sin(m), a=cos(m) | Sine and cosine, calculated component by component from matrix m. |
a=sum(m) | a is the matrix summed column by column m(a is a row vector). |
a=sum(m,dim) | a is the sum along the dimension dim summed matrix m. |
a=rem(m,n) | Remainders if the matrix m is component-wise integer by matrix n is divided component-wise. |
Keywords in Matlab functions
Functions with a fixed number of inputs and outputs:
Header in the programme:
function [output1,output2] = function name (input1, input2)
Saving the function in the file functionname.m
Call from Command window or other function / script:
[output1,output2] = function name (input1, input2)
function | Key term function in the header means that the programme is used as a function with an encapsulated workspace. |
[Output1,Output2] | List of output parameters that are passed by the function, i.e. must be assigned there. |
(Input1, Input2) | List of input parameters that are passed to the function and can be used there. The number of inputs and outputs must match in the programme header and in the call, otherwise an error message will be displayed. |
Functions with a variable number of inputs and outputs:
function [varargout] = function name (varargin)
function | Key term function in the header means that the programme is used as a function with an encapsulated workspace. |
[varargout] | Key term varargout means that a different number of output parameters can be passed depending on the function call. varargout is itself a cell array that must be assigned in the programme text. |
varargout{1}=x | copies the content of the variable x to the first position of the output parameters to be passed |
nargout | key term nargout is a variable that is automatically available in every function and specifies the number of outputs requested in the programme call. |
(varargin) | Key term varargin means that different numbers of input parameters can be passed depending on the function call. varargin is itself a cell array that should be used in the programme text. |
x=varargin{1} | copies the content of the first input passed into the variable x |
nargin | key term nargin is a variable that is automatically available in every function and specifies the number of inputs passed in the programme call. |
Comments in functions and scripts:
% | Key character indicating that everything else in a programme line is considered a comment. |
%% | Key character for the start of a new programme section (cell). |
Case distinctions:
if for a few different cases, switch for many cases:
| General syntax | Example: if |
| if condition Commands end | if a==b c=a/2; end |
| if condition Commands1 else Commands2 end | if a==b |
| if condition1 Commands1 elseif condition2 Commands2 else Commands3 end | if a==b c=a/2; elseif a>b c=b/2; else c=0; end |
switch Expression | str='a' switch str case 'a' x=1 case 'b' x=2 otherwise x=0 end |
Loops
| General syntax | example |
| COUNT LOOP: for variable=expression commands end | o=ones(1,10) for a=2:10 o(a)=2*o(a-1); end |
CONDITIONAL LOOP: while condition | o=1; a=1; while o(a)<1000 a=a+1; o=[o 2*o(a-1)]; end |
COLON AS IMPLICIT LOOP: var=[start value:increment:end value] | a=[1:0.1:2] |
The following options generate the same vector a:
| Colon: | Counting loop: | Conditional loop: |
| a=[1:0.1:2] | a=1; for b=1:10 a=[a a+0.1*b]; end | a=1 while a(end)<2 a=[a a(end)+0.1]; end |
Screen output
; | Suppresses the screen output after a command. |
... | Interrupts a programme line. This makes it easier to write very extensive commands (otherwise Matlab executes a programme line as soon as it is completed with Return). |
echo on | Repeats the executed command on the screen. |
echo off | Switches echo off again. |
clc | Deletes all current screen output so that the input window is empty again. |
pause | Waits for a keystroke before executing the next command. |
pause(10) | Waits 10 seconds before executing the next command. |
disp('hello world') disp(v) | Displays a matrix or character string on the screen without displaying the array name. |
warning('Attention!') | Displays a warning on the screen, the programme sequence is not affected by this. |
error('Attention, error!') | Displays an error message written in red on the screen and cancels the programme. |
type('filename') | Displays the content of the file on the screen. |
lookfor term | Searches all help texts for the specified (English) term and displays the first line of the text on the screen. |
format long, format long e, format short, format short e | Converts how many decimal places are displayed for floating point numbers. |
Data management:
save filename | Saves all current variables in the file filename.mat in the current directory. |
save('filename','var1','var2') alternatively: save filename var1 var2 | Saves only variables var1 and var2 in the file filename.mat. |
save -ascii filename.txt | Saves all current variables as a text file filename.txtwhich can be loaded and further processed by any editor. |
load('filename') | Retrieves all variables saved in filename.mat into the workspace. |
cd subfolder | Changes the current directory to the subfolder subfolder. |
cd .. | Changes the current directory to the parent directory. |
fscanf | Powerful possibility to read any formatted data (many options, please refer to the help if required). |
fprintf | Powerful possibility to save formatted data (many options, please refer to the help if required). |
xlswrite('file.xls',var) | Saves a Matlab variable in an xls file for further processing with Excel. |
var=xlsread('file.xls') | Loads a file created with Excel into the Matlab workspace. |
answer=input('please enter number > | Reads a user input from the keyboard into variable answer variable. |
answer=input('please enter text','s') | Reads a user input from the keyboard as a character string in the variable answer variable. |
Data types
double | Floating point numbers with double precision, standard type for numbers in Matlab |
realmax | Largest positive floating point number that Matlab can calculate with. |
eps | Smallest positive floating point number that Matlab can calculate with. |
Conversion of data types:
double(v) | Converts a variable (vector or matrix) into floating point numbers. |
int8(v), int16(v), int32(v), int64(v) | Converts a variable (vector or matrix) into integers, which are represented with a maximum of 8, 16, 32 or 64 bits. |
logical(v) | Converts a variable (scalar, vector or matrix) into truth values. |
char(v) | Converts a variable (vector) into a character string. |
Tests for data types:
b=islogical(a); | Returns the truth value 1 if a consists of truth values |
b=isnumeric(a); | Returns the truth value 1 if a consists of numbers (floating point numbers, integers, complex numbers). |
b=isfloat(a); | Returns the truth value 1 if a consists of floating point numbers. |
b=ischar(a); | Returns the truth value 1 if a consists of characters. |
b=isa(a,'class-name'); | Returns the truth value 1 if a corresponds to the data type specified with the class-name option, e.g. logical, char, integer, int8, struct. |
b=isnan(a); | Returns a matrix of truth values with the same dimensions as a for each entry 1 is returned for each entry if it is NaN (not a number) - i.e. not a representable number (e.g. after dividing by 0). |
b=isscalar(a); | Returns the truth value 1 if a is a scalar value. |
b=isvector(a); | Returns the truth value 1 if a is a vector. (Note that individual values are also vectors, but matrices are not). |
Character strings (string)
s='bla' | Creates a variable s of the type charthat starts with the string 'bla' is assigned. |
b=blanks(10) | Creates a string of 10 blanks. |
s(2) | Second element (letter) of the string s. |
s=sprintf(format, A); | Writes the content of matrix A formatted into the character string s. |
%g | Assignment for format in sprintf: compact representation of decimal numbers |
%s | Assignment for format in sprintf: Representation of strings |
strcmp(s,'bla') | compares string s with string 'bla' for equality |
strncmp(s,'bla',2) | Compares the first 2 letters of the two strings for equality. |
answer=input('please enter text','s') | Reads a user input from the keyboard as a character string in variable response variable. |
SPARSE MATRICES
S=sparse(M) | Generates a sparse matrix in which only the elements of S are stored together with their indices. |
M=full(S) | Generates from a sparse matrix S the corresponding normal matrix M. |
issparse(s) | Test whether a matrix is sparse |
find | find elements not equal to 0 (as usual) |
Nonzeros | Values of elements not equal to 0 |
speye | generates sparse identity matrix |
spfun | applies function to elements not equal to 0. |
sprand(S) | generates a sparse matrix with the same structure as matrix Sbut with equally distributed random elements |
sprandn(S) | creates a sparse matrix with the same structure as matrix S but normally distributed random elements |
spones | Replaces the elements not equal to 0 with ones |
spy | Visualisation of the sparse-pattern |
structures:
structurname.fieldname=assignment
<spanstyle="colour:maroon;" style="colour: #900030;">structurname(number).fieldname=assignment</spanstyle="colour:maroon;">
Cell arrays:
cellname{number}=assignment
cellname{row,column}=assignment
Searching and sorting
Logical indexing:
L=M>0 | Creates a logical matrix L with the same dimensions as matrix Mwhere for each element of matrix M at the same position a logical 1 if the element is positive and a logical 0. |
v=M(L) | Applies a logical matrix L to a matrix M with the same dimensions. Vector >v contains only those elements of matrix M where at the same position in M a logical 1 in M . |
Search:
ind=find(v) | Returns all indices of the vector v that are not equal to 0. |
ind=find(v,k) | Returns the first k indices of the vector v that are not equal to 0. |
ind=find(v,k,'last') | Returns the last k indices of the vector v that are not equal to 0. |
[row,col]=find(M,...) | Returns the row and column indices of the elements of the matrix M that are not equal to 0. |
[row,col]=find(M,...) | Returns row and column indices and values of the elements of the matrix M that are not equal to 0. |
Sort:
vs1=sort(v1) | sorts the elements of a vector v1 in ascending order |
ms1=sort(m,1) | sorts the elements of each column of the matrix m in ascending order (independent of each other) |
ms2=sort(m,2) | sorts the elements of each row of the matrix m in ascending order(independent of each other) |
msd=sort(m,1,'descend') | sorts the elements of each column of the matrix m in descending order (independent of each other) |
[ms1,index]=sort(m,1) | returns the indices in addition to the sorted matrix |
mr1=sortrows(m1,n) | sorts the rows of the matrix m1 according to their entries in the nth column in ascending order. |
mdesc1=sortrows(m1,-n) | sorts the rows of the matrix m1 according to their entries in the n- column in descending order. |
mr_n1=sortrows(m1,[n,1]) | sorts the rows of the matrix m1 of their entries in the n-th column in ascending order. If the values in the n-th column, these rows are sorted according to the 1st column. |
[mr1,index]=sortrows(m1,n) | also returns a vector of indices. |
Line graph
plot(v) | Returns the values of the vector v against their indices. |
plot(x,y) | Plots the values of the vector y against those of the vector x vector. |
plot(x1,y1,x2,y2) | Combines the plots of y1 against x1 and y2 against x2 in one image. |
plot(x,y,'ro-') | Uses red circles connected with lines to plot y against x (the order of the formatting parameters does not matter - please look up the parameters in the help). |
plot(x,y,'colour',[0.5 0.2 1]) | Uses a line with a self-defined colour to plot y against x against x. The colour vector is made up of the values for [red green blue]which lie between 0 and 1. (Please refer to the help for other line properties, the syntax is always plot(x,y,'property',value). Several properties can be combined. |
loglog(x,y) | Double logarithmic plot of y against x. |
semilogx(x,y) | Plot with logarithmic x- and linear y-axis (semilogy accordingly). |
errorbar(x,y,e) | Carries y against x and provides each data point with symmetrical error bars of length 2e (e upwards and downwards respectively). |
Other graph types
pie(x), pie3(x) | Representation of the vector x as a pie chart or as a 3-dimensional pie chart. |
mesh(x,y,z) | 3-dimensional representation of the matrix z as a mesh model with vectors x and y as axes. x must have the dimension y*x have. (More possibilities in the help). |
surf(x,y,z) | 3-dimensional representation of the matrix z as a coloured surface with vectors x and y as axes. z must have the dimension y*x have. (More possibilities in the help). |
boxplot(x) | Represents x as a boxplot. If x is a matrix, the median, percentiles and outliers are calculated for each column and plotted as a separate "box". |
imagesc(m) | Displays the elements of a 2D matrix in colour-coded form. The smallest element is dark blue in the default colour setting(colormap) |
colormap(grey) | Defines the colours of the colour coding (in this case greyscale). See help for colour selection. |
fill(x,y,colourdef) | Fills an area defined by x,y with the desired colour. Colour definition either by abbreviation for standard colours or in RGB representation |
hist(v) | Represents the histogram of the frequency of occurrence of values in the vector v graphically. Standard version: Divides the value range of the vector hist is called without an output argument, it displays the frequency of occurrence of the classes as a bar graph. |
h=hist(v) | If hist is called with an output argument, it does not produce a graphical output, but returns the vector of frequencies. (Can be combined with multiple input arguments.) |
hist(v,nbins) | Divides the value range of the vector v in nbins classes of equal size. |
hist(v,centres) | Uses the vector centres as the centres of the classes in which the elements of v are divided into. If hist is called without an output argument, it displays the frequency of occurrence of the classes as a bar graph. |
[h,xout]=hist(v) | If hist is called with two output arguments, it does not produce a graphical output, but returns two vectors: the vector h of the frequencies and the vector xout of the class centres. |
Graphics window
figure(2) | Opens a new graphics window and gives it the number 2. |
close(2) | Closes the second graphics window. |
clf | Deletes the contents of the current graph window. |
subplot(m,n,p) | Divides the current graph window into m*n subplots (m next to each other, n below each other) and causes the next plot-command, the p-th sub-image is used (counted line by line). |
xlabel('bla bla') | Labelling of the x-axis (y accordingly). |
title('Great picture') | Image caption. |
axis([xmin xmax ymin ymax]) | Sets the limits between which values are to be plotted graphically. |
axis equal | Makes the graphics window square by scaling the axes equally |
Randomness and statistics
Randomness
r=rand(2,5) | Generates a 2x5 matrix with equally distributed random numbers between 0 and1 |
r=randn(2,5) | Generates a 2x5 matrix with normally distributed random numbers with mean 0 and standard deviation 1. |
p=randperm(n) | Returns a vector p in which the natural numbers 1 to n are in random order. |
Descriptive statistics
mean(m,dim) | Mean value of matrix m along dimension dim (if no dimension is specified: column by column). |
std(m,flag,dim) | Standard deviation of m along dimension dim (if no dimension is specified: columnwise). The flag parameter determines the normalisation: flag=0 for normalisation over N-1, flag=1 for normalisation over N. |
var(m, flag, dim) | Variance of m along dimension dim (if no dimension is specified: column by column). The parameter flag parameter determines the normalisation: flag=0 for normalisation over N-1, flag=1 for normalisation over N. |
median(m,dim) | Median of m along dimension dim (if no dimension is specified: columnwise). |
Z=prctile(x,p) | Calculates for the data vector x (or for each column of the matrix x) the p-th percentile. (Statistics toolbox!) |
min(m,dim), max(m,dim) | Minimum and maximum along dimension dim (if no dimension is specified: column by column). |
h=hist(v,nbins) | Histogram of the frequency of occurrence of values in the vector v where nbins indicates the number of classes into which the range between the minimum and maximum value of v is divided into. Without specifying the output argument h the histogram is displayed on the screen. There are even more options, hist see Help. |
Hypothesis tests
h=ttest(vector,mean) | tests whether the null hypothesis can be rejected that the values contained in the vector vector vector follow a normal distribution with the mean value mean value originate from a normal distribution. The standard significance level is 5%. |
h=ttest(vector, mean, alpha) | as above, but with specification of the significance level alpha |
h=ttest2(vector1,vector2) | tests whether for two samples vector1 and vector2 the null hypothesis that both samples originate from the same distribution can be rejected at the standard significance level of 5%. |
h=ttest2(vector1, vector2, alpha) | as above, but with specification of the significance level alpha |
For all ttest-functions: The return value is
- 1 if the null hypothesis is rejected and thus the alternative hypothesis is accepted (then the data set to be tested originates with α% probability from a distribution with the mean value to be tested).
- 0 if the null hypothesis cannot be rejected.
Curve fitting
[p,S]=polyfit(x,y,n) | Finds the polynomial n-th degree, which describes the curve described by the vectors x and y by minimising the square distance between the measured values and the function values of the polynomial. p specifies the coefficients of the polynomial p₁xn+p₂xn-1+...pnx+pn+1. S is a structure for use with polyval to estimate the quality of the curve fit. |
y=polyval(p,x) | Determines the function values for a polynomial p₁xn+p₂xn-1+...pnx+pn+1, whose coefficients in the vector p for which the vector x specified in the vector x. |
[y,delta]=polyval(p,x,S) | Determines the function values for a polynomial p₁xn+p₂xn-1+...pnx+pn+1 whose coefficients are specified in the vector p for which the vector x specified in the vector x. In addition, with the help of polyfit returns the structure S in the vector delta is a measure of the reliability of the estimate. The range of y-delta to y+delta contains at least 50% of the estimates (with normal distribution). |
Time measurement
tic; toc | stopwatch |
tic | Starts the stopwatch |
toc | Returns the time since the call of tic on the screen. |
t=toc | Writes the time since tic to the variable t |
str=date | Returns a character string with the current date. |
str=clock | Returns a character string with the current date and time. |