MATLAB Fundamentals, Study notes of Software Engineering

This document explains the very basic fundamentals of MATLAB software. The person will be able to write down a very long and meaningful MATLAB code specially in courses related to electrical engineering

Typology: Study notes

2017/2018

Uploaded on 09/27/2018

mimi-chan352
mimi-chan352 🇰🇼

10 documents

1 / 144

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Introduction
to MATLAB
by Prof. M. Zribi
1
Outline
MATLAB Basics
MATLAB Variables
Vectors and Matrices
Strings
MATLAB Built-in Functions
Handling Polynomials Using MATLAB
Script M-files
MATLAB User Defined Functions
Prof. Mohamed Zribi
2
MATLAB Data Files
Plotting Using MATLAB
3D Plotting Using MATLAB
Solving ODEs Using MATLAB
Programming in MATLAB
MATLAB Symbolic Toolbox
Introduction to SIMULINK
Prof. Mohamed Zribi
3
MATLAB Basics
Prof. Mohamed Zribi 4
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download MATLAB Fundamentals and more Study notes Software Engineering in PDF only on Docsity!

Introduction

to MATLAB

by Prof. M. Zribi

1

Outline

MATLAB Basics

MATLAB Variables

Vectors and Matrices

Strings

MATLAB Built-in Functions

Handling Polynomials Using MATLAB

Script M-files

MATLAB User Defined Functions

Prof. Mohamed Zribi

2

^

MATLAB Data Files

^

Plotting Using MATLAB

^

3D Plotting Using MATLAB

^

Solving ODEs Using MATLAB

^

Programming in MATLAB

^

MATLAB Symbolic Toolbox

^

Introduction to SIMULINK

Prof. Mohamed Zribi

3

MATLAB

Basics

Prof. Mohamed Zribi

4

What is MATLAB?

^

MATLAB is a program for doing numerical computation. It wasoriginally designed for solving linear algebra type problemsusing matrices. It’s name is derived from

MAT

rix

LAB

oratory.

^

MATLAB has since been expanded and now has built-infunctions for solving problems requiring data analysis, signalprocessing, optimization, and several other types of scientificcomputations.

It also contains functions for 2-D and 3-D

graphics and animation. Prof. Mohamed Zribi

5

What is MATLAB?

^

The MATLAB environment is command oriented somewhat likeUNIX. A prompt appears on the screen and a MATLABstatement can be entered. When the

key is pressed,

the statement is executed, and another prompt appears. ^

If a statement is terminated with a semicolon (

;^

), no results will

be displayed. Otherwise results will appear before the nextprompt. Prof. Mohamed Zribi

6

What is MATLAB?

^

MATLAB is basically a

high level language

which has many

specialized toolboxes for making things easier for us ^

How high?

Assembly

High Level Languages such as

C, Pascal etc.

MATLAB

Prof. Mohamed Zribi

7

Why MATLAB

^

Compared to other choices: 

C++, Fortran, Java 

Excel, MathCad, Mathematica, Labview ^

MATLAB is a Very High Level Language 

Designed for complex numerical calculations 

Vast array of Toolboxes for different specialties 

Excellent visualization tools 

Symbolic math somewhat awkward 

SIMULINK for modeling dynamic systemsProf. Mohamed Zribi

8

MATLAB Toolboxes

^

Communications ^

Signal Processing ^

Image Processing ^

System Identification ^

Control System ^

Robust Control ^

Curve Fitting ^

Filter Design ^

Fixed-Point ^

Fuzzy Logic ^

Genetic Algorithm ^

Image Acquisition ^

Mapping

^

Neural Network ^

Optimization ^

Parallel Computing ^

Partial Differential Equation ^

Spline ^

Statistics ^

Wavelet

Filter Design

^

Fuzzy Logic ^

μ-Analysis and Synthesis ^

LMI Control ^

Model Predictive Control

MATLAB Toolboxes include: Prof. Mohamed Zribi

13

MATLAB Toolboxes

Prof. Mohamed Zribi

14

MATLAB Toolboxes

Functions in MATLAB toolboxes are used the same asMATLAB core functions, the use of the toolboxes is‘ transparent

’ to the user.

Prof. Mohamed Zribi

15

Starting MATLAB

^

use the icon

^

Or

from

Start Menu

Select

Programs

Select

MATLAB

^

The prompt

should appear in the command

window after a fairly long initialization process:

Prof. Mohamed Zribi

16

MATLAB

Screen

^

Command Window ^

type commands

^

Current Directory ^

View folders and m-files

^

Workspace ^

View program variables ^

Double click on a variableto see it in the Array Editor

^

Command History ^

view past commands ^

save a whole sessionusing diary

MATLAB PromptTells that MATLABis ready for yourcommand

Prof. Mohamed Zribi

17

MATLAB’s ENVIRONMENT

Prof. Mohamed Zribi

18

Desktop Tools

^

Command Window 

type commands ^

Workspace 

view program variables 

clear

to clear

double click on a variable to see it in the Array Editor ^

Command History 

view past commands 

save a whole session using

diary

^

Launch Pad 

access tools, demos and documentation

Prof. Mohamed Zribi

19

MATLAB shortcuts

Help

SIMULINK

Open files

Newfile Prof. Mohamed Zribi

20

MATLAB Operators

(cont.)

Operator

Description

+^

Addition

-^

Subtraction

.*^

Multiplication (element wise)

./^

Right division (element wise)

.^

Left division (element wise)

=^

Assignment operator,e.g. a = b,(assign b to a)

:^

Colon operator (Specify Range )

.^^

Power (element wise)

'^

Transpose

*^

Matrix multiplication

/^

Matrix right division

^

Matrix left division

;^

Row separator in a Matrix

^^

Matrix power

Prof. Mohamed Zribi

25

MATLAB as a CALCULATOR Command window

39*4.4+5ans =

Command window

The MATLAB command

The result.

Prof. Mohamed Zribi

26

MATLAB as a CALCULATOR

Prof. Mohamed Zribi

27

MATLAB as a CALCULATOR >> 8/10ans =

>> 5ansans =*

>> r=8/10r =

>> rr =

>> s=20rs =*

Prof. Mohamed Zribi

28

Order of Precedence( VERY Important to understand!)

•Higher-precedence operations are executed before lower-precedence operations•If two operations have the same precedence, then the expressionis executed from left to right.

PRECEDENCE

OPERATION

First

Parentheses (innermost pair first)

Second

Exponentiation

Third

Multiplication and division

Fourth

Addition and subtraction

Prof. Mohamed Zribi

29

Order of Precedence - Examples

Look at the following

( a=1, b=2, c=4, d=5 )

a + b/c + d

evaluates to

(a + b)/c + d

(a + b)/(c+d)

a + b/(c+d)

Prof. Mohamed Zribi

30

MATLAB as a CALCULATOR

8 / 2

is executed first

>> 7 + 8 / 2ans =

11

Type and press

Enter

Computer response

(7 + 8)

is executed first

>> (7 + 8) / 2ans =

7.

Type and press

Enter

Computer response

27 ^ 1

and

32 ^ 0.

are executed first

/^ is executed next +^

is executed last

>> 27 ^ 1 / 3 + 32 ^ 0.2ans =

**11

27 ^ (1 / 3) + 32 ^ 0.2ans =**

5

(1 / 3)

is executed first

^^

is executed next +^

is executed last

Prof. Mohamed Zribi

31

MATLAB as a CALCULATOR >> 8 + 35ans =*

>> 8 + (35)ans =*

>>(8 + 3)5ans =*

>>4^212 8/42ans =*

>>4^212 8/(42)ans =*

Prof. Mohamed Zribi

32

Entering Commands and Expressions ^

MATLAB retains your previous keystrokes.

^

Use the up-arrow ↑ key to scroll back through thecommands.

^

Press the key once to see the previous entry, and soon.

^

Use the down-arrow

key to scroll forward.

^

Edit a line using the left-arrow

and right-arrow

keys the

Backspace

key, and the

Delete

key.

^

Press the

Enter

key to execute the command.

Prof. Mohamed Zribi

37

Commands for Managing the Work Session clc

clears the command window, but doesn’t eliminate variables

clear

removes all variables from memory

clear var1 var2 var3…

clears specified variables from memory

clear all

removes all variables and functions from memory

who

lists the variables in memory

whos

lists the variables in memory and provides additional information

what

lists the m-files in the current directory

quit

stops MATLAB.

“ellipses” – used to continue your expression onto the next line

dir

Lists the contents of the current working directory

save filename var1 var2….save filename var1… -ascii

Saves variables into the file named filename in MATLAB formatSaves variables into an ASCII formatted file.

diary filenamediary on/off

Starts a diary session that saves Command Window information into a file

Prof. Mohamed Zribi

38

Commands for Managing the Work Session

(cont.)

ls^

Same as dir

type test

Display test.m in command window

delete test

Delete test.m

cd a:

Change directory to a:

chdir a:

Same as cd

pwd

Show current directory

which test

Display current directory path to test.m

more on/off

Enables/disables paged output

ctrl+c

Aborts operation

why

In case you ever needed a reason

which functionPath , addpathpathtool tic

,^ toc

bracketing code to measure execution time

Prof. Mohamed Zribi

39

Special Values •^

pi:

value up to 15 significant digits

•^

i, j: sqrt(-1)

-^

Inf: infinity (such as division by 0)

-^

NaN: Not-a-Number (division of zero by zero)

-^

clock: current date and time in the form of a 6-element rowvector containing the year, month, day, hour, minute, andsecond

-^

date: current date as a string such as

19-Dec-

•^

eps: epsilon is the smallest difference between two numbers

-^

MATLAB Special Variables( do not use as variable names! ) ans: stores the result of an expression

Prof. Mohamed Zribi

40

•^

beep :

make sound

•^

realmin, realmax :

smallest & largest positive real numbers

•^

vitmax :

largest positive integer

•^

nargin, nargout :

number of in (or) out variables in a function

•^

varargin :

variable number of function in arg’s

•^

varaout :

variable number of function out arg’s

MATLAB Special Variable( do not use as variable names! )

Prof. Mohamed Zribi

41

Reserved Words

MATLAB has some special (reserved) words that you may not

use…

forendifwhilefunctionreturnelsifcaseotherwise

switchcontinueelsetrycatchglobalpersistentbreak

Prof. Mohamed Zribi

42

MATLAB

Variables

Prof. Mohamed Zribi

43

MATLAB Variable Names

Variable names are

case sensitive

Variable names can contain up to 63 characters

Variable names must start with a letter

followed by

letters, digits, or underscores.

Prof. Mohamed Zribi

44

Defining Variables

^

No need for types. i.e.,

^

All variables are created with double precision unlessspecified and they are matrices.

^

After these statements, the variables are 1x1 matriceswith double precision

int a;double b;float c;

Example:>>x=5;>>x1=2;

Prof. Mohamed Zribi

49

Variables - Example

^

Don’t have to declare type

^

Don’t even have to initialise

^

Just assign in command window

>> a=12; % variable a is assigned 12

Matlabprompt

assignoperator

suppresscommandoutput

commentoperator

Prof. Mohamed Zribi

50

Variable Name Examples

log(5)ans =

log = 4

% Very bad practice

log =

log(5)??? Index exceeds matrix

dimensions.

clear log>> log(5)ans =

Abc=123Abc =

ABc??? Undefined function orvariable 'ABc'.

Prof. Mohamed Zribi

51

Variables - Example

View variable

contents by simply typing the variable name at

the command prompt

>> a=12;>> aa =

>> a*2a =

Prof. Mohamed Zribi

52

We can manipulate variables stored in the workspace >> b=10;>> c=a+bc =

Prof. Mohamed Zribi

53

Display contents of workspace>>

whos Name

Size

Bytes Class

a^

1x

8 double array

b^

1x

8 double array

c^

1x

8 double array

Grand total is 3 elements using 24 bytes>> Delete variable(s) from workspace >> clear a b;

% delete a and b from workspace

whos>> clear all;

% delete all variables from workspace

whos >>

exist

(‘var’)

%^

Determines if a file or variable exists having the % name ‘

var

’.

Prof. Mohamed Zribi

54

Constants and Functions - Example

pians =

epsans = 2.2204e-016>> sin(pi/2)ans =

1

log(1000)ans =

log10(1000)ans =

3

Prof. Mohamed Zribi

55

Constants - Example

bitmaxans = 9.0072e+015>> epsans = 2.2204e-016>> realminans = 2.2251e-308>> realmaxans = 1.7977e+308>> ansans = 1.7977e+308>> ians =

0 + 1.0000i

infans =

Inf

NaNans =

NaN

Prof. Mohamed Zribi

56

Arrays

^

Arrays can be classified as

vectors

and

matrices

^

Arrays are the fundamental unit of data in MATLAB.

^

Scalars are also treated as arrays by MATLAB (1 row and1 column).

^

Row and column indices of an array start from 1.

Prof. Mohamed Zribi

61

Arrays

^

Scalar:

1 by 1 Array

^

Vector:

Array with one dimension

^

Matrix:

Array with more than one dimension

^

Size

of an array is specified by the number of rows and the number of columns, with the number of rows mentioned first (For example: n x m array).Total number of elements in an array is the product of the number of rows andthe number of columns. Prof. Mohamed Zribi

62

^

Arrays are constructed using brackets and semicolons. All of the elements ofan array are listed in row order. ^

The values in each row are listed from left to right and they are separated byblank spaces or commas. ^

The rows are separated by semicolons or new lines. ^

The number of elements in every row of an array must be the same. ^

The expressions used to initialize arrays can include algebraic operations andall or portions of previously defined arrays.

Prof. Mohamed Zribi

63

Vectors and Matrices

^

MATLAB treats all variables as matrices.

^

Vectors are special forms of matrices and contain only onerow OR one column.

^

Scalars are matrices with only one row AND one column

Prof. Mohamed Zribi

64

Vectors and Matrices - Example

A matrix with only one row is called a row vector. A row

vector can be created in MATLAB as follows (note thatthe commas are optional):

» row_vec = [12 , 14 , 63]row_vec =

Prof. Mohamed Zribi

65

Vectors and Matrices - Example

A matrix with only one column is called a column vector. A

column vector can be created in MATLAB as follows (notethe semicolons): » col_vec = [13 ; 45 ; -2]col_vec =

Prof. Mohamed Zribi

66

Vectors and Matrices - Example

Don’t need to initialise type, or dimensions>>A = [3 2 1; 5 1 0; 2 1 7]A =

square brackets to define matrices

semicolon for next row in matrix

Prof. Mohamed Zribi

67

Vectors and Matrices - Example

A matrix can be created in MATLAB as follows (note the

commas AND semicolons): » matrix1 = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]matrix1 =

Prof. Mohamed Zribi

68

Vectors and Matrices - Example

>> B = [ 1 2 ; 3 4 ] ;B =

>> C = B * B

% or equivalent B^

C =

B

B

Prof. Mohamed Zribi

73

Vectors and Matrices - Example

Notice that the array subscripts in Matlab start from 1 and not0 as is the case in C.Illustration:>> A = [1 2 3 4];>> A(0)

% This command will result in syntax error

The first index is 1 and not 0.>> A(1)ans = 1 Prof. Mohamed Zribi

74

The : operator

^

VERY

important operator in MATLAB

^

Means ‘to’

>> 1:10ans =

>> 1:2:10ans =

Prof. Mohamed Zribi

75

The : operator - Example

x = 1 : 7

% same as

x = [ 1 : 7 ]

x = [ 1 2 3 4 5 6 7]

y = 0 : 3 : 12

y = [ 0 3 6 9 12 ]

y = 0 : 3 : 11

y = [ 0 3 6 9 ]

z = 15 : -4 : 3

z = [ 15 11 7 3 ]

w = 0 : 0.01 : 2

w = [ 0 0.01 0.02 ... 1.99 2.00 ]

Prof. Mohamed Zribi

76

Vectors and Matrices - Example

^

x = [1,2,3]

% vector-row,

^

y=[1;2;3]

% vector-column,

^

x=0:0.1:0.

% vector x=[0,0.1,0.2,0.3....0.8],

^

A = [1,3,5;5,6,7;8,9,10]

% matrix,

^

A(1,2)

% element of matrix, 1. row, 2. column,

^

A(:,2)

% second column of matrix,

^

A(1,:)

% first row of matrix ,

^

C=[A;[10,20,30]]

% matrix with additional row,

^

A(:,2)=[]

% deleting of second column,

^

B=A(2:3,1:2)

% part of matrix,

^

x’

% transpose.

Prof. Mohamed Zribi

77

Manipulating Matrices - Example

Access elements of a matrix

>>A(1, 2)ans= 2 

Remember Matrix(row, column)

Naming convention

Matrix variables

start with a

capital

letter while vectors or scalar variables start with a simpleletter

A =

3

2

1

5

1

0

2

1

7

indices of matrix element(s)

Prof. Mohamed Zribi

78

Manipulating Matrices - Example

A=

[

1

2

3

;

4

5

6

;^

7

8

9];

x

=

A

(

1,

3

)

%^

A(,)

x^

= 3

y

=

A

(

2

,

:

)

%^

selects

the

2

nd

row

y^

= 4

5

6

z

=

A

(

1:

,

1:

)

%^

selects

sub-matrix

z^

= 1

2

3

4

5

6

Prof. Mohamed Zribi

79

Assigning a scalar to a subarray: A scalar value on the right-hand side of an assignment statement is copied into everyelement specified on the left-hand side.

arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12];>> arr4(1:2, 1:2) = 1arr4 =

Manipulating Matrices - Example

Prof. Mohamed Zribi

80