23
1 Introduction to MATLAB (MATrix LABoratory) Presented By: Dr Mostafa Elshahed Asst. Prof. 1 Faculty of Engineering, Cairo University Upon completing this course, the student should be able to: Learn a brief introduction to programming in MATLAB. Create the MATLAB Scripts (m file) and use its help. Define the different Variables and Operations. Formulate the User-Defined Function. Discriminate between different basic flow-control. Construct the line plots, surface plots, and animations. Solve equations and curve fitting using MATLAB. Use MATLAB debugger to fix the errors. Explore Probability and Statistics commands. Utilize some MATLAB toolboxes: Simulink and SimPowerSystems. 2 Faculty of Engineering, Cairo University Dr. Mostafa Elshahed

Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

  • Upload
    hakien

  • View
    228

  • Download
    2

Embed Size (px)

Citation preview

Page 1: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

1

Introduction to MATLAB

(MATrix LABoratory)

Presented By:

Dr Mostafa ElshahedAsst. Prof.

1Faculty of Engineering, Cairo University

Upon completing this course, the student should be able to:

Learn a brief introduction to programming in MATLAB. Create the MATLAB Scripts (m file) and use its help. Define the different Variables and Operations. Formulate the User-Defined Function. Discriminate between different basic flow-control. Construct the line plots, surface plots, and animations. Solve equations and curve fitting using MATLAB. Use MATLAB debugger to fix the errors. Explore Probability and Statistics commands. Utilize some MATLAB toolboxes: Simulink and

SimPowerSystems.

2Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 2: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

2

Textbooks

• A. Gilat , MATLAB: An Introduction with Applications, 4th Ed., John Wiley & Sons, Inc.,2011.

• Getting Started with MATLAB, Mathworks Inc., 2011.

• http://www.cyclismo.org/tutorial/matlab/

3Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Assessment

• Lab Attendance: Two Labs (Two Sheets)

• Grades Policy: (For Part 4 only)

Quiz 05 Grades

Project 05 Grades

-----------------------------------------------

Final Exam 30 Grades

-----------------------------------------------

Total Grade 40 Grades

Dr. Mostafa Elshahed Faculty of Engineering, Cairo University 4

Page 3: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

3

MathWorks®

MATLAB®

R2012a (7.14)

MATLAB

Is an integrated technical computingenvironment that combines numeric computation,advanced graphics and visualization, and a high-levelprogramming language.

The MathWorks, Inc.

High-level language of technical computing

Development environment for engineers, scientists

Interactive tools for design, problem solving

Mathematical function libraries

Graphics and data visualization tools

Custom GUIs

External Interfaces: C, C++, Fortran, Java, COM, Excel, .NET6Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 4: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

4

MATLAB product family

Toolboxes: Collections of specialized Functions

Graphics

2D Graphics3D GraphicsColor & LightingAnimationImage, Audio & Video

Computations

Linear AlgebraData AnalysisPolynomialsInterpolationsSolutions of ODE

External Interfaces

CC++JAVA.netMicorosoft Excel

Parallel ComputingMath, Statistics, and OptimizationControl System Design and AnalysisSignal Processing and CommunicationsImage Processing and Computer VisionTest and Measurement

Built-in Functions

User-written Functions

MATLAB

Computational FinanceComputational Biology

Code Generation and VerificationApplication Deployment

Database Connectivity and Reporting

MATLAB Programming Language

Parallel Computing ToolboxMATLAB Distributed Computing Server

Parallel Computing Symbolic Math ToolboxPartial Differential Equation ToolboxStatistics ToolboxCurve Fitting Toolbox

Optimization ToolboxGlobal Optimization ToolboxNeural Network ToolboxModel-Based Calibration Toolbox

Math, Statistics, and OptimizationControl System ToolboxSystem Identification ToolboxFuzzy Logic Toolbox

Robust Control ToolboxModel Predictive Control ToolboxAerospace Toolbox

Control System Design and Analysis Signal Processing ToolboxDSP System ToolboxCommunications System ToolboxWavelet Toolbox

Fixed-Point ToolboxRF ToolboxPhased Array System Toolbox

Signal Processing and Communications

Image Processing ToolboxComputer Vision System ToolboxImage Acquisition ToolboxMapping Toolbox

Image Processing and Computer Vision

Data Acquisition ToolboxInstrument Control ToolboxImage Acquisition ToolboxOPC ToolboxVehicle Network Toolbox

Test and Measurement

Financial ToolboxEconometrics

ToolboxDatafeed ToolboxDatabase Toolbox

Computational FinanceSpreadsheet Link EX (for Microsoft Excel)

Fixed-Income ToolboxFinancial Derivatives Toolbox

Bioinformatics Toolbox

SimBiology

Computational BiologyMATLAB Coder

HDL CoderHDL Verifier

Filter Design HDL Coder

Code Generation and Verification

MATLAB CompilerMATLAB Builder NE (for Microsoft .NET

Framework)MATLAB Builder JA (for Java language)

MATLAB Builder EX (for Microsoft Excel)Spreadsheet Link EX (for Microsoft Excel)

Application DeploymentDatabase Toolbox

MATLAB Report Generator

Database Connectivity and Reporting

7Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

1. Simulink

2. Simpowersystems

3. Aerospace Simulation

4. Neural Network

5. Parallel Computing

6. Image Acquisition

7. Image processing

8. Genetic Algorithm

9. Fuzzy Logic

10. Database processing

11. Video and Image processing

12. Control System

13. Signal Processing

14. Statistics

15. Financial Toolbox

16. Curve fitting

.

.

.8

Toolboxes provided By MATLAB

Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 5: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

5

Agenda

Introducing MATLAB – Language of technical computing

Minimal MATLAB

9Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Agenda

Introducing MATLAB – Language of technical computing

Minimal MATLAB

MATLAB Desktop

Computing with MATLAB

Array – creation & working

Plotting – creating & visualizing

Automating commands – creating, saving & executing script file

Conditional control statements

Loop control statements

Functions – creating & executing a function file

10Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 6: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

6

Agenda

Introducing MATLAB – Language of technical computing

Minimal MATLAB

MATLAB Desktop

Computing with MATLAB

Array – creation & working

Plotting – creating & visualizing

Automating commands – creating, saving & executing script file

Functions – creating & executing a function file

Conditional control statements

Loop control statements

11Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

The main window characterized by the MATLAB command prompt (>>)

Command Window

This is where you write, edit, create, and save your own script or programs in files called m-files.

Editor Window

This is where all your files from the current directory are listed.

Current Directory

All commands typed on MATLAB prompt in the command window get recorded, even across multiple session in this window.

Command History

This subwindow lists all variables that you have generated so far along with there type and size.

Workspace

MATLAB - Desktop

12Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 7: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

7

MATLAB - Desktop

The main window characterized by the MATLAB command prompt (>>)

Help Window

13Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Scripts (MATLAB m files)

14Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Scripts are:

collection of commands executed in sequencewritten in the MATLAB editorsaved as MATLAB files (.m extension

To create an MATLAB file

from command-line »edit mostafa.mor click

Page 8: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

8

Scripts (MATLAB m files)

15Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

RUN

Agenda

Introducing MATLAB – Language of technical computing

Minimal MATLAB

MATLAB Desktop

Computing with MATLAB

Array – creation & working

Plotting – creating & visualizing

Automating commands – creating, saving & executing script file

Functions – creating & executing a function file

Conditional control statements

Loop control statements

16Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 9: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

9

Arithmetic Operator & Their Precedence

Operations Operators Examples

AdditionSubtractionMultiplicationRight DivisionLeft DivisionExponentiation

Precedence Order

Operators

1

234

Parentheses ( ). For nested parentheses, the innermost are executed first.Exponentiation, ^Multiplication, *; Division, /,\Addition, +; Subtraction, -

help precedence

17Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Mathematical Functions

Trigonometry

sindcosdtandcotdsecdcscd

Degree

sincostancotseccsc

sinhcoshtanhcothsechcsch

asinacosatanacotasecacsc

Basic Hyperbolic Inverse

Radian

Basic

Exponential

exploglog10log2sqrt

Complex

absconjimagrealangle

Matrix

dettracerankinvexpmsqrtm

help <type function name>

18Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 10: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

10

Predefined Variables and Keywords

ans

pieps

infi,jNaN

Predefined Variables

break case catch classdef continue else elseif end forfunction global if otherwise parfor persistent returnspmd switch try while

Keywords

iskeyword

help <Predefined Variable Name>

19

iskeyword(‘keyword’) 1 or 0

lookfor keyword

Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Useful CommandsThe two commands used most by Matlab users are:

20

>>help functionname >>lookfor keyword

clc Clears the command window; Semicolon suppresses screen printing

or denotes a new row in an array, Comma or Space separates elements

in a row: Colon generates an array having

regularly spaced elements

Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 11: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

11

Agenda

Introducing MATLAB – Language of technical computing

Minimal MATLAB

MATLAB Desktop

Computing with MATLAB

Vector and Array – creation & working

Plotting – creating & visualizing

Automating commands – creating, saving & executing script file

Functions – creating & executing a function file

Conditional control statements

Loop control statements

21Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

• No need for types. i.e.,

• All variables are created with double precision unless specified and they are matrices.

• After these statements, the variables are 1x1 matrices with double precision.

int a;double b;float c;

>>x=5;>>x1=2;

22

Variables

Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 12: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

12

Use meaningful names for variables

MATLAB variable names

– must begin with a letter

– can contain any combination of letters, numbers and underscore (_)

– must be unique in the first 31 characters

MATLAB is case sensitive: “name”, “Name” and “NAME” are considered different variables.

Never use a variable with the same name as a MATLAB command.

Naming convention: use lowercase letters

23

Variables

Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Managing Variables

clearclear x y zclear allwhowhos

save

load

Clears the workspace, all variables are removed from memoryClears only variables x, y, and zClears all variables and functions from workspaceLists variables currently in the workspaceLists variables currently in the workspace with their sizes together with information about their bytes and classSave workspace variables to MAT-file >>save(‘MOSTAFA’) MOSTAFA.mat>>save matlab.matLoad data from MAT-file into workspace>>load(‘MOSTAFA’)

Command Outcome

24Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 13: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

13

Overview

5

5745 7 4

5 10 566 4 67 78 86

Scalar of 1 X 1 Row Vector of 1 X 3 Column vector of 3 X 1

One Dimensional Matrix of 3 X 3

5 10 56 85 236 4 6 23 27 78 86 53 6

5 14 12 10 566 10 504 4 6

89 0 0

Two Dimensional Matrix of 3 X 5

3X5X2

5 10 56 85 236 4 6 23 27 78 86 53 6

5 14 12 10 5660

5 14 12 10 56890

Three Dimensional Matrix of 3 X 5

3X5X3

25Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Creation

One Dimensional Array

variable_name = [ type vector elements ]

Two Dimensional Array

variable_name = [1st row elements; 2nd row elements; 3rd row elements; ... ; last row elements]

from a known list of numbers with constant spacing by specifying the first term, the spacing,

and the last term

Known lists of numbers

26Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 14: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

14

Creation

Creating a vector with constant spacing by specifying the first term, the spacing, and the last term:

variable_name = [m:q:n]

or

variable_name = m:q:n

m = first term

q = spacing

n = last term

: (colon operator)Constant spacing

Creating a vector with linear (equal) spacing by specifying the first and last terms, and the number of terms:

variable_name = linspace(xi, xf, n)

xi = first element

xf = Last element

n = number of elements

linspaceConstant spacing

27Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

• a vector x = [1 2 5 1]

x =1 2 5 1

• a matrix X = [1 2 3; 5 1 4; 3 2 -1]

X =1 2 35 1 43 2 -1

• transpose y = x’ y =

1251

28

Creation

Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 15: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

15

>> x = [1 2]; y = [4 5]; z=[ 0 0]

>> A = [ x y]

1 2 4 5

>> B = [x ; y]

1 2

4 5

29

C = [x y ;z] Error:??? Error using ==> vertcat CAT arguments dimensions are not consistent.

Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Creation

Array Operators

+ Addition- Subtraction* Multiplication/ Division\ Left Division.* Element-by-element multiplication./ Element-by-element division.\ Element-by-element left division.^ Element-by-element power‘ Transpose

Operations Operation

30Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 16: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

16

Address vector

>> ve = [35 46 78 23 5 14 81 3 55]

ve =

35 46 78 23 5 14 81 3 551 2 3 4 5 6 7 8 9

position or index of element

Data Manipulation

31Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Addressing vector : (colon operator)

Data Manipulation

Addressing matrix : (colon operator)

A(:,n) Refers to the elements in all the rows of column n of the matrix A.

A(n,:) Refers to the elements in all the columns of row n of the matrix A.

A(:,m:n) Refers to the elements in all the rows between columns m and n of the matrix A.

A(m:n,:) Refers to the elements in all the columns between rows m and n of the matrix A.

A(m:n,p:q)Refers to the elements in rows m through n and columns p through q of the matrix A.

32Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 17: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

17

33

Address

Data Manipulation

Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

• The matrix indices begin from 1 (not 0 (as in C))• The matrix indices must be positive integer

34

Given:

A(-2), A(0)

Error: ??? Subscript indices must either be real positive integers or logicals.

A(4,2)Error: ??? Index exceeds matrix dimensions.

Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Data Manipulation

Page 18: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

18

Comment used in MATLAB • “%” is the neglect sign for MATLAB (equivalent of “//”

in C). Anything after it on the same line is neglected by MATLAB compiler.

• Sometimes slowing down the execution is done deliberately for observation purposes. You can use the command “pause” for this purpose

35

>>pause %wait until any key>>pause(3) %wait 3 seconds

Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

• sort

• sortrows

• issorted 1 or 0

36

For vectors, SORT(X) sorts the elements of X in ascending order.For matrices, SORT(X) sorts each column of X in ascending order.

>> x= 1:5x =

1 2 3 4 5>> sort(x)ans =

1 2 3 4 5>> sort(x,'descend')ans =

5 4 3 2 1

Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Built in Functions

Page 19: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

19

Limit and Integration

37Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Differentiation

38Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 20: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

20

Initializing with Built-in Functions

zeros(n)

zeros(n,m)

ones(n)

ones(n,m)

ones(size(array))

eye(n)

eye(n,m)

length(vector)

Length(array)

size(array)

zeros(size(array))

39Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Generating Vectors from functions• zeros(M,N) MxN matrix of zeros

• ones(M,N) MxN matrix of ones

• rand(M,N) MxN matrix of uniformly distributed random

numbers on (0,1)

x = zeros(1,3)

x =

0 0 0

x = ones(1,3)

x =

1 1 1

x = rand(1,3)

x =

0.9501 0.2311 0.6068

40Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 21: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

21

Matrices Operations

41

Given A and B:

Addition Subtraction Product Transpose

Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

The use of “.” – “Element” Operation

42

K= x^2Error:??? Error using ==> mpower Matrix must be square.B=x*yError:??? Error using ==> mtimes Inner matrix dimensions must agree.

A = [1 2 3; 5 1 4; 3 4 -1]A =

1 2 35 1 43 4 -1

y = A(3 ,:)

y= 3 4 -1

b = x .* y

b=3 8 -3

c = x . / y

c= 0.33 0.5 -3

d = x .^2

d= 1 4 9

x = A(1,:)

x=1 2 3

Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 22: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

22

Matrix Operation(cont…)

• transpose(‘)

• tril: lower triangular matrix

• triu: upper triangular matrix

• rank: show rank of matrix

• det: determinant of matrix

• diag: returns principle diagonal

• inv: inverse of the matrix

• eig: eign value(matrix must be square matrix)

43Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Displaying Data/Text

44Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Page 23: Introduction to MATLAB - Cairo Universityscholar.cu.edu.eg/?q=mostafa_elshahed/files/lec_1_0.pdf · Introduction to MATLAB (MATrixLABoratory) ... Final Exam 30 Grades----- Total Grade

23

Displaying Data/Text(cont…)

45Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed

Thank You…

46Faculty of Engineering, Cairo UniversityDr. Mostafa Elshahed