introduction to matlab - kcir.pwr.edu.plkcir.pwr.edu.pl/~mucha/scieng/lecture7.pdf · introduction...

Post on 08-Jul-2018

242 Views

Category:

Documents

3 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Introduction to MATLAB

Mariusz Janiakp. 331 C-3, 71 320 26 44

c© 2015 Mariusz JaniakAll Rights Reserved

Contents

1 Introduction

2 Matlab essentials

3 Matlab matrices

4 Control flow

5 Plotting

Introduction

Matlab combines a desktop environment tuned for iterativeanalysis and design processes with a programming language thatexpresses matrix and array mathematics directly.1

Matlab stands for MATrix LABoratory

Developed by Mathworks.

Computing and programming environment

Programming language (script, JIT compiler)

Multiplatform (Windows, Mac, Linux)

Proprietary software (expensive)

Web page

www.mathworks.com

1 The MathWorks, Inc.

Introduction

Matlab in general

Professionally built (rigorously tested and fully documented)

Interactive apps (off-the-shelf)

Ability to scale (clusters, GPUs and clouds)

Deploy to enterprise applications (production ready)

Run on embedded devices (convert to C/C++ and HDL)

Integrate with Model-Based Design (Simulink)

Introduction

Typical Matlab domains

Data Analytics

Control Systems

Robotics

Deep Learning

Computer Vision

Signal Processing

Wireless Communications

Quantitative Finance and Risk Management

Introduction

Popular alternatives to Matlab

Octave (www.gnu.org/software/octave)

Scilab (www.scilab.org)

Python + SciPy (www.scipy.org)

SageMath (www.sagemath.org)

Introduction

Matlab desktop

Introduction

Main components

Command Window – the main window for executingcommands (Matlab’s sandbox)

Workspace – display and manage a list of the currently defiedvariables (name, value, class)

Current Folder – file explorer, points the working directory

Command History – display a list of the last commandsentered (enable rerun)

Editor – advanced text editor for writing and running scriptsand functions (debugger integrated)

Help Browser – extensive Matlab documentation (start here)

Matlab essentials

Matlab can be used interactively in the Command Window(interpreted environment)

Matlab can be used as a calculatorBasic commandswho, whos – list current variablesclear – remove variable(s) from workspacehelp – display help text (for specified functionality)doc – opens the Help Browserclc – clear Command Windowquit, exit – quit Matlab session

Ctrl+c interrupt a running program (eg. infinite loop)

Matlab essentials

Help facilities in principle contains all information about Matlab

Use help to request info on a specific function.

h e l p ' f u n c t i o n n a m e '

It gives a short description of the function, the syntax, andother closely related help functions.

Use lookfor to find functions by keywords

l o o k f o r ' t o p i c '

It gives the list of all possible function names which contain thespecific search word

Use doc to open the on-line version of the manual

doc ' f u n c t i o n n a m e '

Matlab essentials

Matlab data types

2

2The MathWorks, Inc.

Matlab essentials

Variables

Created by using an assignment statement

Weak dynamic typing

Have not to be previously declared (preallocate for speed)Identifier names

Must start with a letter followed by letters, digits, andunderscores (without spaces),Can contain up to namelengthmax (63) characters,Is case-sensitiveShould not be reserved word or name of a built-invariable/functions

Matlab essentials

Special variables and constants

ans – most recent answer (variable created automatically)

eps – accuracy of floating-point precision

i, j – the imaginary unit√−1

pi – the number π

inf, Inf – infinity

nan, Nan – undefined numerical result (not a number)

realmin – largest finite floating point number

realmax – smallest positive normalized floating point number

intmin – smallest integer value

intmax – largest positive integer value

Matlab essentials

Expressions is a legal combination of numerical values,mathematical operators, variables, and function calls

Long statements can be continued on to the next line by usingellipsis – three or more periods (...)Semicolon (;)

indicates end of statement (in line multiple assignments)suppress and hide the Matlab output for an expression

CommentsPercent (%) – comment linePercent curly bracket (%{ %}) – block comments

The format command can be used to specify the output formatof expressions (format short – default, scaled fixed pointformat with 5 digits)

Matlab essentials

Arithmetic operators

Symbol Role Info+ Addition, unary plus plus, uplus- Subtraction, unary minus minus, uminus* Matrix multiplication mtimes.* Element-wise multiplication times/ Matrix right division mrdivide./ Element-wise right division rdivide\ Matrix left division mldivide.\ Element-wise left division ldivide^ Matrix power mpower.^ Element-wise power power’ Complex conjugate transpose ctranspose.’ Transpose transpose

Matlab essentials

Relational operators

Symbol Role Info== Equal to eq~= Not equal to ne> Greater than gt>= Greater than or equal to ge< Less than lt<= Less than or equal to le

Matlab essentials

Logical operators

Symbol Role Info& Logical AND and| Logical OR or&& Logical AND (with short-circuiting)|| Logical OR (with short-circuiting)~ Logical NOT not

Matlab essentials

Special Characters

Symbol Name Role@ At symbol Function handle construction and reference. Period or dot Decimal point

Element-wise operationsStructure field accessObject property or method specifier

... Ellipsis Line continuation, Comma Separator: Colon Vector creation

IndexingFor-loop iteration

; Semicolon Signify end of rowSuppress output of code line

( ) Parentheses Operator precedenceFunction argument enclosureIndexing

[ ] Square brackets Array constructionArray concatenationEmpty matrix and array element deletionMultiple output argument assignment

{ } Curly brackets Cell array assignment and contents

Matlab essentials

Special Characters (cont.)

Symbol Name Role% Percent Comment

Conversion specifier%{ %} Percent curly bracket Block comments! Exclamation point Operating system command? Question mark Metaclass for Matlab class’ ’ Single quotes Character array constructor" " Double quotes String constructor (since release 2017a)N/A Space character Separator~ Tilde Logical NOT

Argument placeholder= Equal sign Assignment

Matlab essentials

M-File (1)

Standard text file with *.m extension

Allow to reuse sequences of commands by storing them inprogram filesScript – the simplest type of program

store commands exactly as one would type them at thecommand lineoperate on variables in the workspaceno input or output arguments

Function – sub-program with function statementinclude any valid expressions, control flow statements,comments, blank lines, and nested functionscan pass input values and return output valuesoperate on local variables

Matlab essentials

M-File (2)

Function syntax

f u n c t i o n [ y1 , . , yN ] = myfun ( x1 , . ,xM)

Declares a function named myfun that accepts inputs x1,. ,xMand returns outputs y1, . ,yN

This declaration statement must be the first executable line ofthe function

Valid function names begin with an alphabetic character, andcan contain letters, numbers, or underscores

The name of the file should match the name of the firstfunction in the file

Files can include multiple local functions or nested functions

Matlab essentials

Load and store workspace variables

Save workspace variables to file

s a v e ( f i l e n a m e )s a v e ( f i l e n a m e , v a r i a b l e s )...

Load variables from file into workspace

l o a d ( f i l e n a m e )l o a d ( f i l e n a m e , v a r i a b l e s )...

If filename is a MAT-file, then load(filename) loadsvariables in the MAT-File into the Matlab workspaceIf filename is an ASCII file, then load(filename) creates adouble-precision array containing data from the file

Matlab essentials

Simple I/O

Request user input

x = i n p u t ( prompt )s t r = i n p u t ( prompt , ' s ' )

Displays the text in prompt and waits for the user to input avalue. The user can enter expressions, like pi/4 or rand(3),and can use variables in the workspace. With ’s’ returns theentered text, without evaluating the input as an expression.

Display value of variable

d i s p (X)

Displays the value of variable X without printing the variablename

Matlab essentials

GUI

Graphical User Interfaces

Typically contains controls such as menus, toolbars, buttons,and sliders.ToolsApp Designer – environment for building Matlab apps(layout, behavior)GUIDE – tools to design user interfaces for custom apps (layout)Matlab contains built-in functionality to help you create theGUI for your app programmatically (layout, behavior)

Matlab matrices

All Matlab variables are matrices

A vector is a matrix with one row or one column

A scalar is a matrix with one row and one column

A character string is a row vector of characters (ASCII)

The rules of linear algebra apply

Matlab matrices

Element-by-element creation of vectors and matrices (1)

Vector and matrix elements are enclosed in square brackets

Row vector – elements separated with spaces or commas

v1 = [ 1 2 3 ] % row v e c t o r 1 x3v2 = [ 1 , 2 , 3 ] % row v e c t o r 1 x3

Column vector – elements separated with newline or semicolon

v3 = [ 123 ] % column v e c t o r 3 x1

v4 = [ 1 ; 2 ; 3 ] % column v e c t o r 3 x1

Matlab matrices

Element-by-element creation of vectors and matrices (2)

Matrix – rows separated with newline or semicolon, rowelements with spaces or commas

m1 = [ 1 2 3 ; 4 5 6 ; 7 8 9 ] % m a t r i x 3 x3m2 = [ 1 , 2 , 3 ; 4 , 5 , 6 ; 7 , 8 , 9 ] % m a t r i x 3 x3m3 = [ 1 2 3

4 5 67 8 9 ] % m a t r i x 3 x3

m4 = [ 1 , 2 , 34 ,5 ,67 , 8 , 9 ] % m a t r i x 3 x3

Matlab matrices

Matrix indexing (1)

Indexing into a matrix is a means of selecting a subset ofelements from the matrix

Several indexing styles

Indexing is also closely related to vectorization

Elements of the vectors and matrices are addressed withFortran-like subscript notation eg. v(1), m(1,2)

Notation is clear from context, but it can be confused withfunction call

Index start form 1 (unlike C/C++)

Matlab matrices

Matrix indexing (2)Indexing vectors (extraction, substitution)

scalar subscript

v ( 3 ) % Thi rd e l e m e n t

vector subscript

v ( [ 1 5 ] ) % F i r s t , and f i f t h e l e m e n t s

colon notation

v ( [ 1 : 3 ] ) % F i r s t t h r e e e l e m e n t s

operator end

v ( end ) % L a s t e l e m e n tv ( 5 : end ) % F i f t h through t h e l a s tv ( 1 : end−1) % F i r s t th rough t h e next−to− l a s t

Matlab matrices

Matrix indexing (3)Indexing matrix (extraction, substitution)

with two subscripts (similar to vector)

A( 2 , 4 ) % Element i n row 2 , column 4A ( 2 : 4 , 1 : 2 ) % Sub−m a t r i xA ( 3 , : ) % Thi rd row

linear indexing – one subscript

Matlab matrices

Matrix indexing (4)Indexing matrix (extraction, substitution)

Logical indexing – closely related to the find function eg.A(A > 5) is equivalent to A(find(A > 5))

A(A > 12) % Elements o f A g r e a t e r than 12B( i s n a n (B) ) = 0 % R e p l a c e a l l NaN e l e m e n t s w i t h z e r o

Matlab matrices

Colon notationThe colon is one of the most useful operators in MatlabCreate vectors, subscript arrays, and specify ’for’ iterationSyntax

x = j:k creates a unit-spaced vector xx = j:i:k creates a regularly-spaced vector xA(:,n) indexing, the nth column of matrix AA(m,:) indexing, the mth row of matrix AA(:,:,p) the pth page of three-dimensional array AA(:) reshapes A into a single column vectorA(:,:) reshapes A into a two-dimensional matrixA(j:k) index A with vector j:k, equivalent to

[A(j), A(j+1), ..., A(k)]A(:,j:k) all subscripts in the first dimension,

index second dimension, equivalent to[A(:,j), A(:,j+1), ..., A(:,k)]

Matlab matrices

Transposition (1)

Transpose vector or matrix

B = A . '

B = t r a n s p o s e (A)

Complex conjugate transpose

C = A '

C = c t r a n s p o s e (A)

Matlab matrices

Transposition (2)

transpose() vs ctranspose()

>> A = [0−1 i 2+1 i ;4+2 i 0−2 i ]A =

0.0000 − 1 .0000 i 2 .0000 + 1.0000 i4 .0000 + 2.0000 i 0 .0000 − 2 .0000 i

>> B = A . '

B =0.0000 − 1 .0000 i 4 .0000 + 2.0000 i2 .0000 + 1.0000 i 0 .0000 − 2 .0000 i

>> C = A '

C =0.0000 + 1.0000 i 4 .0000 − 2 .0000 i2 .0000 − 1 .0000 i 0 .0000 + 2.0000 i

Matlab matrices

Create and combine arrays

zeros Create array of all zerosones Create array of all onesrand Uniformly distributed random numberstrue Logical 1 (true)false Logical 0 (false)eye Identity matrixdiag Create diagonal matrix or get diagonal elements of matrixblkdiag Construct block diagonal matrix from input argumentscat Concatenate arrays along specified dimensionhorzcat Concatenate arrays horizontallyvertcat Concatenate arrays verticallyrepelem Repeat copies of array elementsrepmat Repeat copies of array

Matlab matrices

Create grids

linspace Generate linearly spaced vectorlogspace Generate logarithmically spaced vectorfreqspace Frequency spacing for frequency responsemeshgrid 2-D and 3-D gridsndgrid Rectangular grid in N-D space

Matlab matrices

Determine Size and Shape

length Length of largest array dimensionsize Array sizendims Number of array dimensionsnumel Number of array elementsisscalar Determine whether input is scalarisvector Determine whether input is vectorismatrix Determine whether input is matrixisrow Determine whether input is row vectoriscolumn Determine whether input is column vectorisempty Determine whether array is empty

Matlab matrices

Linear algebra (selected)

inv Matrix inversepinv Moore-Penrose pseudoinverseeig Eigenvalues and eigenvectorsdet Matrix determinantnull Null spacerank Rank of matrixorth Orthonormal basis for range of matrixcond Condition number with respect to inversiontrace Sum of diagonal elementssvd Singular value decompositionlu LU matrix factorizationqr Orthogonal-triangular decompositionchol Cholesky factorization

Matlab matrices

Complex numbers (1)

Matlab automatically performs complex arithmetic

Complex numbers are represented in rectangular form

The imaginary unit√−1 is denoted either by i or j

Both or either i and j can be reassigned

It is a good idea to reserve either i or j for the unit imaginaryvalue

√−1

>> ians =

0.0000 + 1.0000 i

>> i = 5 ;>> ii =

5

Matlab matrices

Complex numbers (2)

abs Absolute value and complex magnitudeangle Phase anglecomplex Create complex arrayconj Complex conjugatecplxpair Sort complex numbers into complex conjugate pairsi Imaginary unitimag Imaginary part of complex numberisreal Determine whether array is realj Imaginary unitreal Real part of complex numbersign Sign function (signum function)unwrap Correct phase angles to produce smoother phase plots

Matlab matrices

Characters and strings

Character arrays and string arrays provide storage for text data

A character array is a sequence of characters, just as a numericarray is a sequence of numbers

c = ' H e l l o World '

A string array is a container for pieces of text, it provides a setof functions for working with text as data (starting in R2017a,strings can be created using double quotes)

s t r = ” G r e e t i n g s f r i e n d ”

Extensive support for string manipulation: create, concatenate,find and replace, join, split, edit, compare, regular expression(read doc)

Control flow

Conditional statements, loops, branching

if, elseif, else Execute statements if condition is truefor Loop to repeat specified number of timesparfor Parallel for loopswitch, case, otherwise Execute one of several groups of statementstry, catch Execute statements and catch resulting errorswhile Loop to repeat when condition is true

break Terminate execution of loopcontinue Pass control to next iteration of loopend Terminate block of codepause Stop MATLAB execution temporarilyreturn Return control to invoking function

Control flow

if, elseif, else

i f e x p r e s s i o n

s t a t e m e n t s

e l s e i f e x p r e s s i o n

s t a t e m e n t s

e l s e

s t a t e m e n t s

end

if...end evaluates an expression, andexecutes a group of statements when theexpression is true

The elseif and else blocks are optional.The statements execute only if previousexpressions in the if...end block are false

An if block can include multiple elseifblocks

An expression is true when its result isnonempty and contains only nonzeroelements

Control flow

for

f o r i n d e x = v a l u e s

s t a t e m e n t s

end

for...end executes a group of statementsin a loop for a specified number of timesvalues has one of the following formsinitV:endV – increment the indexvariable from initV to endV by 1, andrepeat execution of statements until indexis greater than endVinitV:step:endV – increment index bythe value step on each iteration, ordecrements index when step is negativevalArray – create a column vector,index, from subsequent columns of arrayvalArray on each iteration

Control flow

parfor

p a r f o r l o o p v a r = i n i t v a l : e n d v a l ; s t a t e m e n t s ; endp a r f o r ( l o o p v a r = i n i t v a l : endva l , M) ; s t a t e m e n t s ; end

Executes a series of statements for values of loopvar betweeninitval and endval, inclusive, which specify a vector ofincreasing integer values

The loop runs in parallel when you have the Parallel ComputingToolbox or when you create a MEX function or standalone codewith MATLAB Coder.

Iterations are not executed in a guaranteed order

Executes statements in a loop using a maximum of M workers orthreads, where M is a nonnegative integer.

Control flow

switch, case, otherwise

s w i t c h s e x p r e s s i o n

c a s e c e x p r e s s i o n

s t a t e m e n t s

c a s e c e x p r e s s i o n

s t a t e m e n t s

...

o t h e r w i s e

s t a t e m e n t s

end

Evaluates an s expression and choosesto execute one of several groups ofstatements

Each choice is a case

The switch block tests each case untilone of the c expressions is true

When a c expression is true, Matlabexecutes the corresponding statementsand exits the switch block

The otherwise block is optional,Matlab executes the statements onlywhen no case is true.

Control flow

try, catch

t r ys t a t e m e n t s

c a t c h e x c e p t i o ns t a t e m e n t s

end

Executes the statements in the try block andcatches resulting errors in the catch block

This approach allows to override the defaulterror behavior for a set of program statements

If any statement in a try block generates anerror, program control goes immediately tothe catch block, which contains custom errorhandling statements

exception is an MException object thatallows to identify the error

Both try and catch blocks can containnested try/catch statements.

Control flow

while

w h i l e e x p r e s s i o n

s t a t e m e n t s

end

Evaluates an expression, and repeats theexecution of a group of statements in aloop while the expression is true.

An expression is true when its result isnonempty and contains only nonzeroelements, otherwise the expression is false

Control flow

Vectorization (1)

The process of revising loop-based, scalar-oriented code to useMatlab matrix and vector operations

The loop is executed by the Matlab kernel, which is muchmore efficient at evaluating a loop in interpreted Matlab codeAdvantagesAppearance – vectorized mathematical code appears more likethe mathematical expressions found in textbooksLess Error Prone – vectorized code is often shorter, thusintroduces fewer opportunities to programming errorsPerformance – vectorized code often runs much faster than thecorresponding code containing loops

Most built-in function support vectorized operations

Control flow

Vectorization (2)

Loop-based computation of sine on specified interval

i = 0 ;f o r t = 0 : . 0 1 : 1 0

i = i + 1 ;y ( i ) = s i n ( t ) ;

end

Vectorized version

t = 0 : . 0 1 : 1 0 ;y = s i n ( t ) ;

Plotting

2-D and 3-D Plots

Use plots to visualize dataPlot typesLine Plots – linear, log-log, semi-log, error bar plotsPie Charts, Bar Plots, and Histograms – proportion anddistribution of dataDiscrete Data Plots – stem, stair, scatter plotsPolar Plots – plots in polar coordinatesContour Plots – 2-D and 3-D isoline plotsVector Fields – comet, compass, feather, quiver and streamplotsSurfaces, Volumes, and Polygons – gridded surface andvolume data, ungridded polygon dataAnimation – animating plotsImages – read, write, display, and modify images

Plotting

Line Plots

plot plot3 semilogx semilogy loglog errorbar

fplot fplot3 fimplicit

Pie Charts, Bar Plots, and Histograms

area pie pie3 bar barh bar3

bar3h histogram histogram2 pareto

Plotting

Discrete Data Plots

stairs stem stem3 scatter scatter3 spy

plotmatrix heatmap

Polar Plots

polarplot polarhistogram polarscatter compass ezpolar

Plotting

Contour Plots

contour contourf contour3 contourslice fcontour

Vector Fields

quiver quiver3 feather streamslice streamline

Plotting

Surface and Mesh Plots

surf surfc surfl ribbon pcolor fsurf

fimplicit3 mesh meshc meshz waterfall fmesh

Animation

animatedline comet comet3

Images

image imagesc

Plotting

Line and Symbol Types (1)

Line Style Description’-’ Solid line’--’ Dashed line’:’ Dotted line’-.’ Dash-dotted line’none’ No line

Color Description’r’ Red’g’ Green’b’ Blue’y’ Yellow’m’ Magenta’c’ Cyan’w’ White’k’ Black

Plotting

Line and Symbol Types (2)

Marker Description Marker Description’o’ Circle ’^’ Upward-pointing triangle’+’ Plus sign ’v’ Downward-pointing triangle’*’ Asterisk ’>’ Right-pointing triangle’.’ Point ’<’ Left-pointing triangle’x’ Cross ’p’ Five-pointed star (pentagram)’s’ Square ’h’ Six-pointed star (hexagram)’d’ Diamond

Plotting

Multiple plots per figure window (1)

subplot – create a matrix of plots in a single figure window

s u b p l o t (m, n , p )s u b p l o t (m, n , p , ' r e p l a c e ' )s u b p l o t (m, n , p , ' a l i g n ' )s u b p l o t (m, n , p , ax )

Divides the current figure into an m-by-n grid and creates axesin the position specified by p. Matlab numbers subplotpositions by row. The first subplot is the first column of the firstrow, the second subplot is the second column of the first row,and so on

Plotting

Multiple plots per figure window (2)

s u b p l o t ( 2 , 1 , 1 ) ;x = l i n s p a c e ( 0 , 1 0 ) ;y1 = s i n ( x ) ;p l o t ( x , y1 )

s u b p l o t ( 2 , 1 , 2 ) ;y2 = s i n (5* x ) ;p l o t ( x , y2 )

Plotting

Plot annotation

axis Set axis limits and aspect ratiosgrid Display or hide axes grid linesgtext Add text to figure using mouselegend Add legend to axestext Add text descriptions to data pointsxlabel Label x-axisylabel Label y-axistitle Add title

The End

Thank you for your kind attention.

top related