5 views

Uploaded by Marco

Lez Matlab

Lez Matlab

© All Rights Reserved

- EEM496 Communication Systems Laboratory - Experiment0- Introduction to Matlab, Simulink, And the Communication Toolbox
- 1934015040
- Familiarization to MATLAB
- forsageep
- MATLAB Lecture 4 1
- L6_GEO5336_DIP_Notes.pdf
- MatLabSlides.pdf
- Matlab Notehis
- matlab_tutorial.pdf
- 2E1215_L1
- forsageep (1).doc
- matlabD
- laporan matlab baru.docx
- matdem
- Lab1
- Intro Matlab Feb 2010
- Manual
- Matlab Course Overview 1
- Applied Physics Exp 3- Intro to Matlab
- Matlab introduction

You are on page 1of 94

INTRODUCTION

to the use of MATLAB

L. Savoldi, R. Bonifetto

Dipartimento Energia

Content

1.

2.

3.

4.

An introduction to MATLAB

The MATLAB interfaces

Variables, vectors and matrices

Using operators

1. Introduction to MATLAB

What is MATLAB?

Dipartimento Energia

numerical computation, data analysis,

visualisation and algorithm development

MATLAB provides functions that operate on

Integer, real and complex numbers

Vectors and matrices

Structures

1. MATLAB Functionality

Built-in Functionality includes

Data analysis

Graphics and visualisation

and hundreds of other functions

Dipartimento Energia

Image processing

Signal Processing

Optimization

ANN...

* but we have to pay for these extras

1. MATLAB paradigm

MATLAB is an interactive environment

Commands are interpreted one line at a time

Commands may be scripted to create your own functions or

procedures

Dipartimento Energia

Variables are typed, but variable names may be reused for different

types

Basic data structure is the matrix (MATrix LABoratory...)

Matrix dimensions are set dynamically

Operations on matrices are applied to all elements of a matrix at once

Removes the need for looping over elements one by one!

Makes for fast & efficient programmes

To Start

On Windows XP platform select

Start->Programs->MATLAB->MATLAB R2010a

Dipartimento Energia

To stop (nicely)

Select File

Dipartimento Energia

Workspace

Command Window

Command History

7

1. Window Components

Dipartimento Energia

Workspace Displays any variables created (Matrices,

Vectors, Singles, etc.)

Command History - Lists all commands previously entered.

Array Editor. This will give you

an Excel-like view of your

data.

8

Pressing the up arrow in the command window will bring

up the last command entered

Dipartimento Energia

past type the first letter and press the up arrow.

The current working directory should be set to a directory

of your own

1. The .m files

Dipartimento Energia

You can write the sequence of the needed operations in

a command file, to be saved with the proper extension:

e.g.: mickey.m

To open or edit an .m file:

>> edit

mickey.m

Dipartimento Energia

11

Variables

Names

Can be any string of upper and lower case letters along with

numbers and underscores but it must begin with a letter

Reserved names are IF, WHILE, ELSE, END, SUM, etc.

Names are case sensitive

Dipartimento Energia

Value

This is the data the is associated to the variable; the data is accessed

by using the name.

Re-assignment is done silently there are no warnings if you

overwrite a variable with something of a different type.

12

Singletons

To assign a value to a variable use

the equal symbol =

Dipartimento Energia

>> A = 32

simply type the name in

13

To make another variable equal to

one already entered

Dipartimento Energia

>> B = A

you change the original value

Note: using ; suppresses output

14

The value of two variables can be added

together, and the result displayed

Dipartimento Energia

>> A = 10

>> A + A

variable

>> A = 10

>> B = A + A

15

2.1 Vectors

A vector is a list of numbers

Dipartimento Energia

16

2.1 Vectors

Dipartimento Energia

content

17

2.1 Vectors

Dipartimento Energia

using the transpose operator

18

Dipartimento Energia

2.1 Vectors

Different ways to assign a vector:

By listing components

vector = [2,3,4,5,6,7,8];

By assigning a rule:

vector = [2:8];

with the instruction linspace:

vector = linspace(2,8,7);

2.1 Matrices

A MATLAB matrix is a rectangular array of numbers

Dipartimento Energia

MATLAB allows you to work with a whole array at a time

2.1 Matrices

You can create matrices (arrays) of any size using a

combination of the methods for creating vectors

Dipartimento Energia

then ; to define a new row

21

2.1 Matrices

You can also use built in functions to create a matrix

>> A = zeros(2, 4)

creates a matrix called A with 2 rows and 4 columns containing the

value 0

>> A = zeros(5) or >> A = zeros(5, 5)

creates a matrix called A with 5 rows and 5 columns

Dipartimento Energia

>> ones(rows, columns)

>> rand(rows, columns)

Rows then the second as the number of Columns

22

You can use the command clear all to delete all the

variables present in the workspace

You can also clear specific variables using:

Dipartimento Energia

23

An Element is a single number within a matrix or vector

To access elements of a matrix type the matrices name

followed by round brackets containing a reference to the row

and column number:

Dipartimento Energia

you reference a value by Row, Column

24

1st

Excel

2nd

Dipartimento Energia

2nd

MATLAB

1st

In Excel (Column, Row):

D3

>> results(3, 4)

25

The referenced element can also be changed

Dipartimento Energia

>> results(3, 4) = 10

or

>> results(3,4) = results(3,4) * 100

26

You can also access multiple values from a Matrix using

the : symbol

Dipartimento Energia

>> Variable_Name(RowNumber, :)

27

To access all rows of a column

Dipartimento Energia

28

These reference methods can be used to change the

values of multiple matrix elements

To change all of the values in a row or column to zero use

Dipartimento Energia

>> results(:, 3) = 0

29

To overwrite a row or column with new values

Dipartimento Energia

>> results(:, 3) = [1; 1; 1; 1; 1; 1; 1]

NOTE: Unless you are overwriting with a single value the data entered must

be of the same size as the matrix part to be overwritten.

30

To access consecutive Rows or

Columns use : with start and end

points:

Dipartimento Energia

Multiple Rows:

>> Variable_Name(start:end, :)

Multiple Columns:

>> Variable_Name(:, start:end)

31

To access multiple non consecutive

Rows or Columns use a vector of

indexes (using square brackets [])

Multiple Rows:

Dipartimento Energia

Multiple Columns:

>>Variable_Name(:, [index1, index2, etc.])

32

The same referencing can be used to change multiple

Rows or Columns

Dipartimento Energia

>> results([3,6], :) = 0

>> results(3:6, :) = 0

33

MATLAB syntax contains pre-defined special matrices:

Dipartimento Energia

matrix with all 1

zeros(num_rows, num_columns) or zeros(num_rows_columns)

matrix with all 0

eyes(num_rows_columns) identity matrix

rand(num_rows, num_columns)

MATLABs Array Editor allows you to copy data from an

Excel spreadsheet in a very simple way

In Excel select the data and click on copy

Dipartimento Energia

Double click on the variable you would like to store the data in

This will open the array editor

In the Array Editor right click in the first element and select

Paste Excel Data

35

Dipartimento Energia

36

The colon : is actually an operator, that generates a row vector

This row vector may be treated as a set of indices when accessing a

elements of a matrix

The more general form is

Dipartimento Energia

[start:stepsize:end]

>> [11:2:21]

11

13

>>

15

17

19

21

>> [22:-2.07:11]

22.00

19.93

>>

17.86

15.79

13.72

11.65

Dipartimento Energia

2.4 Concatenation

The square brackets [] are the concatenation operator.

So far, we have concatenated single elements to form a

vector or matrix.

The operator is more general than that for example we

can concatenate matrices (with the same dimension) to

form a larger matrix

Variables that are currently in the workspace can be saved and

loaded using the save and load commands

Dipartimento Energia

>> save File_Name [variable variable ]

>> load File_Name [variable variable ]

39

Some exercises...

Assign in an array-smart form the matrix:

Dipartimento Energia

Dipartimento Energia

3. More Operators

41

Mathematical Operators:

Dipartimento Energia

Add: +

Subtract: Divide: ./

Multiply: .*

Power: .^ (e.g. .^2 means squared)

operations will be performed

Note that preceding the symbol / or * or ^ by a . means

that the operator is applied between pairs of

corresponding elements of vectors of matrices

42

Simple mathematical operations are easy in MATLAB

The command structure is:

>> Result_Variable =

Variable_Name1 operator Variable_Name2

Dipartimento Energia

Excel:

MATLAB:

>> C = A + B

>> C = (A + 10) ./ 2

43

You can apply single values to an entire matrix

Dipartimento Energia

E.g.

>> data = rand(5,1)

>> A = 10

>> results = data + A

44

Or, if two matrices/vectors are the same size, you can

perform these operations between them

Dipartimento Energia

>> results2 = rand(5,1)

>> results3 = results + results2

45

Dipartimento Energia

way to more useful operations

>> results = zeros(3, 5)

>> results(:, 1:4) = rand(3, 4)

>> results(:, 5) = results(:, 1) + results(:, 2) + results(:, 3) + results(:, 4)

or

>> results(:, 5) = results(:, 1) .* results(:, 2) .* results(:, 3) .* results(:, 4)

NOTE: There is a simpler way to do this using the Sum and Prod functions,

this will be shown later.

46

Dipartimento Energia

>> results(:, 1:4) = rand(3, 4)

>> results(:, 5) = results(:, 1) + results(:, 2) + results(:, 3) + results(:, 4)

47

You can perform operations on a matrix - you are very

likely to use these

Matrix Operators:

Dipartimento Energia

Matrix Multiply: *

Matrix Right Division: /

Example:

48

Dipartimento Energia

Multiplication of matrices with * calculates inner

products between rows and columns

To transpose a matrix, use

det(A) calculates the determinant of a matrix A

inv(A) calculates the inverse of a matrix A

and so on

You can use Logical Indexing to find data that

conforms to some limitations

Dipartimento Energia

Logical Operators:

Less Than: <

Greater Than or Equal To: >=

Less Than or Equal To: <=

Is Equal: ==

Not Equal To: ~=

50

For example, you can find data that is above a certain limit:

>> r = results(:,1)

>> ind = r > 0.2

>> r(ind)

Dipartimento Energia

ind is the same size as r and contains zeros (false) where the data does not

fit the criteria and ones (true) where it does, this is called a Logical Vector.

r(ind) then extracts the data where ones exist in ind

Use of find(condition)

51

>> r = results(:,1)

>> ind = r > 0.2

Dipartimento Energia

>> r(ind)

52

Boolean Operators:

AND: &

OR: |

NOT: ~

Dipartimento Energia

53

Using a combination of Logical and Boolean operators we can select

values that fall within a lower and upper limit

Dipartimento Energia

>> r = results(:,1)

>> ind = r > 0.2 & r <= 0.9

>> r(ind)

>> (x<0)*1

Returns

1 if x is negative

0 if x is positive

Equal condition is written ==

More later...

54

Some exercises...

Dipartimento Energia

4 Functions

A function performs an operation on the input variable

you pass to it

Passing variables is easy, you just list them within round

brackets when you call the function

Dipartimento Energia

function_Name(input)

>> function_Name(matrix(:, 1))

or

>> function_Name(matrix(:, 2:4))

56

4 Functions

The result of the function can be stored in a variable

Dipartimento Energia

e.g.

>> mresult = mean(results)

You can also tell the function to store the result in parts of a

matrix

>> matrix(:, 5) = function_Name(matrix(:, 1:4))

57

4 Functions

To get help with using a function enter

>> help function_Name

Dipartimento Energia

and what it does

58

Dipartimento Energia

4 Functions

MATLAB has many built in functions which make it easy to perform a variety of

statistical operations

sum Sums the content of the variable passed

prod Multiplies the content of the variable passed

mean Calculates the mean of the variable passed

median Calculates the median of the variable passed

mode Calculates the Mode of the variable passed

std Calculates the standard deviation of the variable passed

sqrt Calculates the square root of the variable passed

max Finds the maximum of the data

min Finds the minimum of the data

size Gives the size of the variable passed

sort Sorts the vector in increasing or decreasing order

unique Sorts the vector in increasing or decreasing order removing

duplicate elements

find(condition) Returns the location of the array elements satisfying the

logical condition

rand Returns random real numbers between 0 and 1

round, floor, ceil Rounds to the closest integer number

59

4 Special functions

There are a number of special functions that provide

useful constants

Dipartimento Energia

pi

= 3.14159265.

i or j = square root of -1

Inf

= infinity

NaN

= not a number

4 Functions

Passing a vector to a function like sum, mean, std will

calculate the property within the vector

Dipartimento Energia

>> sum([1,2,3,4,5])

= 15

>> mean([1,2,3,4,5])

=3

61

4 Functions

Dipartimento Energia

calculated over the columns

62

4 Functions

To change the direction of the calculation to the other

dimension (columns) use:

>> function_Name(input, 2)

Dipartimento Energia

>> function_Name(input, [], 2)

63

4 Functions

From Earlier

>> results(:, 5) = results(:, 1) + results(:, 2) + results(:, 3) + results(:, 4)

or

>> results(:, 5) = results(:, 1) .* results(:, 2) .* results(:, 3) .* results(:, 4)

Dipartimento Energia

>> results(:, 5) = sum(results(:, 1:4), 2)

or

>> results(:, 5) = prod(results(:, 1:4), 2)

64

4 Functions

Dipartimento Energia

can now take the

mean and standard

deviation of the data,

and add them to the

array

65

4 Functions

You can find the maximum and minimum of some data

using the max and min functions

Dipartimento Energia

>> max(results)

>> min(results)

66

4 Functions

We can use functions and logical indexing to extract all the results

for a subject that fall between 2 standard deviations of the mean

Dipartimento Energia

>> r = results(:,1)

>> ind = (r > mean(r) 2*std(r)) & (r < mean(r) + 2*std(r))

>> r(ind)

67

4 Building functions

Particular type of script files, starting with the

keyword

function

Inputs

Dipartimento Energia

Outputs

function

[<out1>,...,<outn>]=<functionname>(<in1>,...,<inn>)

% Function help content

<body of the function>

<out1>=...;

<outn>=...;

end

68

4 Building functions

Call to a function:

[<OUT1>,...,<OUTn>]=<functionname>(<IN1>,...,<I

Nn>);

Dipartimento Energia

<IN> can be different from <in>

The function has its own workspace!

global <variablename>

69

4 Building functions

Functions can be used if:

Dipartimento Energia

They are saved into working directory

Matlab function name: in that case, your new

function will be used instead of Matlab one (local

functions are dominant wrt predefined ones)

Type help <nameofyourfunction> before saving

your function

70

4 Building functions

1) Define the function as an instruction in the script:

a) fun='1./(1+x.^2);

b) fun=inline('1./(1+x.^2)', 'x');

c) fun=@(x)[1./(1+x.^2)]; %(anonymous function)

Dipartimento Energia

Plot the function (define vector x and/or its first and last

points x1 and x2: x= x=linspace(x1,x2)):

a) y=fun(x); plot(x,y);

b) y=feval(fun,x); plot(x,y);

c) fplot(fun, [x1, x2]);

d) fplot('1./(1+x.^2)',[x1, x2]); %(if the function has not

been defined before)

71

4 Building functions

Dipartimento Energia

without being called!!!

prompt or from a suitable script

72

5 Plotting

The plot function can be used in different ways:

>> plot(data)

>> plot(x, y)

>> plot(data, r.-)

Dipartimento Energia

Colour: r, b, g, c, k, y etc.

Point style: . + * x o > etc.

Line style: - -- : .-

73

5 Plotting

A basic plot

>> x = [0:0.1:2*pi]

>> y = sin(x)

>> plot(x, y, r.-)

1

0.8

0.6

0.4

0.2

Dipartimento Energia

0

-0.2

-0.4

-0.6

-0.8

-1

74

5 Plotting

Plotting a matrix

MATLAB will treat each column as a different set of data

0.9

0.8

0.7

Dipartimento Energia

0.6

0.5

0.4

0.3

0.2

0.1

10

75

5 Plotting

Dipartimento Energia

title

legend

axis

xlabel

ylabel

76

5 Plotting

>> x = [0:0.1:2*pi];

>> y = sin(x);

Sin Plots

2

1.5

>> hold on

Dipartimento Energia

1

0.5

sin(x)

2*sin(x)

-0.5

-1

>> xlabel(x);

-1.5

>> ylabel(y);

-2

3

x

77

5 Plotting

Plotting data

0.9

0.8

0.7

Dipartimento Energia

0.6

0.5

0.4

>> plot(results, 'b*')

>> hold on

>> plot(mean(results, 2), r.-)

0.3

0.2

0.1

10

78

5 Plotting

Error bar plot

>> errorbar(mean(data, Mean

2),teststd(data,

[], 2))

results with error bars

1

0.9

0.8

Dipartimento Energia

0.7

0.6

0.5

0.4

0.3

0.2

0.1

10

12

79

5 Plotting

Dipartimento Energia

You can close all the current plots using close all

80

pause: pauses the execution of the script; notice that

variables are not updated in the workspace!

Dipartimento Energia

for timeInSeconds seconds

... + new line: first line continues in new one

help <command>: shows the help of that command

81

Dipartimento Energia

Not only

in

Matlab!

ctrl + x cut selection

ctrl + v paste selection

ctrl + z undo

ctrl + s save current file

ctrl + a select all

alt+ F4 close current window

ctrl + F4 close current script in the editor

ctrl + r comment line

ctrl + t uncomment line

(up arrow) recalls previous command typed

in command line

82

Conditions

Boolean statements

(x<0)*1

Returns

Dipartimento Energia

1 if x is negative

0 if x is positive

If statements

if (<condition1>)

<actions1>

elseif (<condition2>)

<actions2>

else

<actions3>

end

83

Loops

Dipartimento Energia

For loops

for (<condition>)

<actions>

end

While loops

while (<condition>)

<actions>

end

Do not use single character variables:

counter ii and not i

84

Loop breakers

Dipartimento Energia

break

stops the execution of the loop; after this statement is

passed, the first line after the end of the loop will be

executed

return

stops the execution of the script; after this statement

is passed, the first line after the call to the function (or

script) will be executed

The use of these two commands makes the debug and

error tracing much difficult: they can always be

substituted by if - else statements and this option is

to be preferred in all codes

85

Dipartimento Energia

eval(<string>);

executes the string as if it were a code line

Allows flexible operations in loops

Use of

cd <directorypath>

to move to folder in directorypath

cd ..

to move one folder up

See folder use_eval (Matlab session)

86

Debug (I)

If an error stops the computation, detailed error report

is provided in Matlab command prompt in red

characters

It allows the full mapping of the error as it shows the

line containing the error also inside nested function

Dipartimento Energia

dimensions, min and max: look for NaN!) after the

code crash!

87

Debug (II)

It is possible to run a Matlab script in Debug

mode; it allows to

Dipartimento Energia

see the value of each variable in real time

breakpoint, and then:

F5 key to run until the next breakpoint

F10 key to run line by line

F11 key to enter in Debug mode inside the

function contained in the line

88

Figures are important for engineers to show results!

Dipartimento Energia

plot(<xx>,<yy>);

OK!

Useless figure!

89

Handles

Handles are used to set or get values for object properties

set(<handle>,<propertyname>,<propertyvalue>);

get(<handle>,<propertyname>);

Dipartimento Energia

Example:

H1=plot(time,pressure);

set(H1,color,g);

gca: graphical current axis

gcf: graphical current figure

90

Other plots

subplot(<row>,<column>,<number>)

loglog(<xx>,<yy>);

semilogx(<xx>,<yy>) and semilogy(<xx>,<yy>);

Dipartimento Energia

errorbar(<xx>,<yy>,<ye->,<ye+>);

bar(<array>);

polar(,r);

(Matlab session)

91

Dipartimento Energia

plotyy(<xx1>,<yy1>, <xx2>,<yy2>);

Useless figure!

OK!

session)

92

.m

Script files (matlab codes)

Functions

.fig

Matlab figure files (editable)

Dipartimento Energia

.eps

Figure files (to be read with GhostView free

software)

.mat

Complex (structured) data files

.dat, .txt

Data files

93

Special commands

<inputvalue>=input(<variablename> = ');

waits for the user to type a value for variable

variablename to be assigned to inputvalue

Execute cmd statements:

!del <filename>.<extension>

Dipartimento Energia

!<file1>.bat

!<file2>.exe

executes the 2 .bat (or .exe) files sequentially

!<file1>.bat &

!<file2>.exe &

executes the 2 .bat (or .exe) files in 2 different parallel windows

94

- EEM496 Communication Systems Laboratory - Experiment0- Introduction to Matlab, Simulink, And the Communication ToolboxUploaded bydonatello84
- 1934015040Uploaded byOscar Trujillo Rodriguez
- Familiarization to MATLABUploaded byJonMarcoReyes
- forsageepUploaded byMarioEmadAyyad
- MATLAB Lecture 4 1Uploaded byAbdul Bari
- L6_GEO5336_DIP_Notes.pdfUploaded byMohamed El-Mutasim El-Feel
- MatLabSlides.pdfUploaded byDanilo Pequeno
- Matlab NotehisUploaded byMohd Rashdan
- matlab_tutorial.pdfUploaded byPrasad Kavthakar
- 2E1215_L1Uploaded byajitjk123
- forsageep (1).docUploaded byJo Jabal
- matlabDUploaded bylibrospiratas
- laporan matlab baru.docxUploaded byAnonymous 8cT9Hsebyt
- matdemUploaded byGITAM UNIVERISTY
- Lab1Uploaded byRodrigo Samico
- Intro Matlab Feb 2010Uploaded byDong Yan
- ManualUploaded byNadir ali
- Matlab Course Overview 1Uploaded byozoemena29
- Applied Physics Exp 3- Intro to MatlabUploaded byLearner eagle
- Matlab introductionUploaded byImran Parvez
- 01 Matlab IntroUploaded byEmilio M. B Castro
- Matlab 1Uploaded byGülçin Köse
- TutorialMATLAB_13_final.pdfUploaded byFiterlinge Sousa
- matlabUploaded byMunish Kumar Dogra
- Introduction to MATLABUploaded bytausif87
- 1 9 OriginalUploaded byecitrux
- KG_ 2019 _B04_01_EnUploaded byMikko Loren
- MatlabUploaded bymamamedusa
- MatLapUploaded byYahia Mustafa Alfazazi
- LAB1Uploaded byMuhammad Bilal Junaid

- Aipmt 2010 ScreeningUploaded byManjunath@116
- A14-DOMM-I-(ME)-04-05-2018-(Supple)Uploaded byMilan Motta
- AssignmentSpecification_2Uploaded byBrian French
- MCP41XXX-42XXXUploaded byOscar Mauricio Sarmiento Urbina
- EMark DP - 10 WattUploaded byJose Diaz
- WT AssignmentUploaded byScholar Delhi
- ReadMe.txtUploaded byRenzo C. Lozano
- gremath_set01Uploaded bystepannp
- CX-One Introduction GuideUploaded byluckyh234
- msg03802Uploaded byRohit Basavaraj
- Mustang Series M114-1 or M6114-1 (Globe), M1114-1 or M61114-1 (Angle) Installation InstructionsUploaded byWatts
- extrusionUploaded bypepe
- GDJP CO-PO Mapping and Justification (1)Uploaded bykarthikeyanme
- Artificial Bee Colony Algorithm Based Optimal Reactive Power Flow of Two-terminalUploaded byJaol1976
- Using ExcelUploaded byelcidv091
- 78023041 Ospf Lab Opnet It GuruUploaded byKarthik Rama
- PE Index for Mechanical EngineersUploaded byAjaya Dhakal
- Fuel Gas System DescriptionUploaded byParmeshwar Nath Tripathi
- BLOWFISH(Bruce Schneier)Uploaded byKiran Mayee
- Rothera Test JurnalUploaded byAzra Zahrah Nadhirah Ikhwani
- 5988-9262ENUploaded byAndre Coutinho
- Lta Dc m&w Wen DazhiUploaded byjohnkoh99
- Catalog Phoenix ContactUploaded byOae Florin
- Finalise Numerical.pptxUploaded bySiti Hanum
- Mathematic Model Paper For Medical and Engineering Entrance ExamUploaded byRoshni Mahapatra
- Wh Vacuum in Steam TurbineUploaded bymiths_0087
- doc36784.pdfUploaded bykadam_nitsi2046
- Reliance Training 03 HiEUploaded byAjaykumar Singh
- JEE_Main_Paper_1_Code_D_Solutions_v2.pdfUploaded byvishnu
- Geological and Structural Setting of Wadi Hodein AreaUploaded bygeo_mms