Transcript Slide 1

MATLAB Introduction

• Main Features – Simple programming rules – Extended accuracy – Continuity among integer, real and complex values – Comprehensive mathematical library – Extensive graphics tools – Linkages with other languages – Transportability across environment – MATLAB scripts will work on PC, UNIX, Mac

• Typical uses include: – 􀃎 Math and computation – 􀃎 Algorithm development – 􀃎 Modelling, simulation and prototyping – 􀃎 Data analysis, exploration and visualization – 􀃎 Scientific and engineering graphics – 􀃎 Application development, including Graphical User Interface (GUI) building

The Advantages of MATLAB

• • • • • • • • • Ease of Use. Platform Independence Predefined Function. Device-Independent Plotting. Graphical User Interface. MATLAB Compiler. a fraction of the time it would take to write a program in a scalar non-interactive language such as C, C++ or Fortran.

MATLAB is the tool of choice for high-productivity research, development and analysis

Disadvantage

• it is an interpreted language and therefore can execute more slowly than compiled languages. • a full copy of MATLAB is five to ten times more expensive than a conventional C or Fortran compiler.

Starting MATLAB

• On UNIX : type matlab at command prompt • Click on the MATLAB icon if you are on a PC • Mac can probably do both… • Issues on startup – MATLAB needs a connection to the license server – Check internet connection – Too many users can use all available licenses

 The name MATLAB stands for MATRIX LABORATORY  It was developed by John Little and Cleve Moler of MathWorks, Inc.

 MATLAB was originally written to provide easy access to the matrix computation software packages LINPACK and EISPACK.

• MATLAB is a high-level language whose basic data type is a matrix that does not require dimensioning. • There is no compilation and linking as is done in high-level languages, such as C or FORTRAN.

• Computer solutions in MATLAB seem to be much quicker than those of a high-level language such as C or FORTRAN. • All computations are performed in complex-valued double precision arithmetic to guarantee high accuracy.

• MATLAB has a large collection of toolboxes in a variety of domains. • Some examples of MATLAB toolboxes are control system, signal processing, neural network, image processing, and system identification. • The toolboxes consist of functions that can be used to perform computations in a specific domain.

• • When MATLAB is invoked, the command window will display the prompt >>.

• MATLAB is then ready for entering data or executing commands. • To quit MATLAB, type the command

exit

or

quit

• MATLAB has on-line help. To see the list of MATLAB’s help facility, type

help For eg help fft

• Scalars are thought of as a 1-by-1 matrix. Vectors are considered as matrices with a row or column.

• Storage of data and variables is allocated automatically once the data and variables are used.

• MATLAB statements are normally of the form:

variable = expression

Starting MATLAB

• Once MATLAB is running the GUI (Graphical User Interface) will appear – Default Window apperance

• Command Window – Main window in MATLAB – Commands entered here

Starting MATLAB

Starting MATLAB

• MATLAB displays >> prompt when ready for a command – Will have no >> prompt when processing commands – Newer versions also say “Ready” or “Busy” in lower left corner of GUI – Can use arrow keys to work through command history and modify commands • Essentially the same as UNIX command prompt

• “MATrix LABoratory” • Powerful, extensible, highly integrated computation, programming, visualization, and simulation package • Widely used in engineering, mathematics, and science • Why?

• Interactive code development proceeds incrementally; excellent development and rapid prototyping environment

• Basic data element is the auto-indexed array • This allows quick solutions to problems that can be formulated in vector or matrix form • Powerful GUI tools • Large collection of

toolboxes

: collections of topic-related MATLAB functions that extend the core functionality significantly

MATLAB Toolboxes Math and Analysis Optimization Requirements Management Interface Statistics Neural Network Symbolic/Extended Math Partial Differential Equations PLS Toolbox Mapping Spline Data Acquisition and Import Data Acquisition Instrument Control Excel Link Portable Graph Object

Signal & Image Processing Signal Processing Image Processing Communications Frequency Domain System Identification

Higher-Order Spectral Analysis System Identification Wavelet Filter Design

Control Design

Control System Fuzzy Logic Robust Control μ-Analysis and Synthesis Model Predictive Control

Intro MATLAB

Toolboxes, Software, & Links

Intro MATLAB

•

MATLAB System

Language:

arrays and matrices, control flow, I/O, data structures, user defined functions and scripts

• Working Environment:

editing, variable management, importing and exporting data, debugging, profiling

• Graphics system:

2D and 3D data visualization, animation and custom GUI development

• Mathematical Functions:

basic ( sum

,

sin ,…) to advanced ( fft

,

inv

, Bessel functions

, …)

• API:

can use MATLAB with C, Fortran, and Java, in either direction

Desktop Tools (Matlab v6)

• 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

Data Types

• logical • char • CELL • structure • Java Classes • Function handle • ARRAY • NUMERIC ------------------------int,single,double

Variable Basics

>> 16 + 24 ans = 40 >> product = 16 * 23.24

product = 371.84

no declarations needed mixed data types

>> product = 16 *555.24; >> product product = 8883.8

semi-colon suppresses output of the calculation’s result

Intro MATLAB

>> clear

Variable Basics

clear

>> product = 2 * 3^3; removes all variables; removes only x and y >> show_i = i^2; complex numbers (

i

or

j

) require >> save three_things no special handling >> clear >> load three_things >> who Your variables are: comp_sum product show_i >> product product = 54 >> show_i show_i = -1 use

save / load

are used to retain/restore workspace variables

home

to clear screen and put cursor at the top of the screen Intro MATLAB

MATLAB Data

•

The basic data type used in MATLAB is the double precision array

• No

declarations

needed: MATLAB automatically allocates required memory • Resize arrays dynamically • To reuse a variable name, simply use it in the left hand side of an assignment statement • MATLAB displays results in scientific notation o Use

File/Preferences

and/or

format

function to change default  short (5 digits), long (16 digits)  format short g; format compact (my preference) Intro MATLAB

• A matrix • may be entered as follows: A = [1 2 3 2 3 4 3 4 5]; may be entered as follows: • A = [1 2 3; 2 3 4; 3 4 5];

• A row vector B with four elements • B = [ 6 9 12 15 18 ] • can be entered in MATLAB as B = [6 9 12 15 18]; or • B = [6 , 9,12,15,18]

• The row vector B can be turned into a column vector by

transposition

, which is obtained by typing • C = B’ • The above results in • C = 6 9 12 15 18

• Other ways of entering the column vector C are • C = [6 9 12 15 18] • or • C = [6; 9; 12; 15; 18]

• • MATLAB is case sensitive in naming variables, commands and functions.

• Thus b and B are not the same variable. If you do not want MATLAB to be case sensitive, you can use the command

casesen off

• To obtain the size of a specific variable, type

size ( )

. For example, to find the size of matrix A, you can execute the following command: • size(A)

• a vector x = 1 2 5 1

Matrices

x = [1 2 5 1] • a matrix x = [1 2 3; 5 1 4; 3 2 -1] x = 1 2 3 5 1 4 3 2 -1 • transpose y = x.’ y = 1 2 5 1

• x(i,j) subscription • whole row • whole column Matrices

y=x(2,3) y = 4 y=x(3,:) y = 3 2 -1 y=x(:,2) y = 2 1 2

Operators (arithmetic)

+ addition Subtraction • Multiplication / division ^ power ‘ complex conjugate transpose .* ./ .^ .‘ element-by-element mult element-by-element div element-by-element power transpose

| ~ == equal ~= not equal

Operators (relational, logical)

pi 3.14159265… < less than j imaginary unit, <= less than or equal  greater than i same as j >= greater than or equal & AND OR NOT  1

Generating Vectors from functions

• zeros(M,N) MxN matrix of zeros • ones(M,N) MxN matrix of ones • rand(M,N) numbers MxN matrix of uniformly distributed random 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

• plot • stem • grid • xlabel • ylabel • title • subplot • figure • pause

Graph Functions (summary)

linear plot discrete plot add grid lines add X-axis label add Y-axis label add graph title divide figure window create new figure window wait for user response

>>a=1 a = 1 >> b=4 b = 4 >> c=a+b c = 5 >> d=cos(a) d = 0.5403

To create variables

>>t=[1 2 3 4 5] t = 1 2 3 4 5 >>t=[1 2 3 4 5]; >> t=1:5 t = 1 2 3 4 5 %equally spaced arrays >> t=1:0.5:4 t = 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000

>>Whos %To know the variables typed so far Name Size Bytes Class Attributes a 1x1 8 double b 1x1 8 double c 1x1 8 double d 1x1 8 double t 1x6 48 double

One and two dimentional arrays

>>data=rand(2,2) data = 0.8147 0.1270

0.9058 0.9134

>>size(data) ans = 2 2 >>x=3+4i x = 3.0000 + 4.0000i

>>a=[1 2 3;4 5 6;7 8 9] a =

1 2 3 4 5 6 7 8 9

>>a(2,3) ans =6 >>b=a' b =

1 4 7 2 5 8 3 6 9 >>c=a*b c = 14 32 50 32 77 122 50 122 194

>>c=a.*b c =

1 8 21 8 25 48

21 48 81

>> data=rand(5,5) data = 0.5313 0.4235 0.4401 0.9436 0.2891

0.3251 0.0908 0.5271 0.6377 0.6718

0.1056 0.2665 0.4574 0.9577 0.6951

0.6110 0.1537 0.8754 0.2407 0.0680

0.7788 0.2810 0.5181 0.6761 0.2548

>> data(1:3,2:end) ans = 0.4235 0.4401 0.9436 0.2891

0.0908 0.5271 0.6377 0.6718

0.2665 0.4574 0.9577 0.6951

>> data(1:2,:)=0 data = 0 0 0 0 0 0 0 0 0 0 0.1056 0.2665 0.4574 0.9577 0.6951

0.6110 0.1537 0.8754 0.2407 0.0680

0.7788 0.2810 0.5181 0.6761 0.2548

>> a=1.5

a =1.5000

>> whos Name Size Bytes Class Attributes a 1x1 8 double >>format long >>1/7 ans =0.142857142857143

>>format short >> 1/7 ans =0.1429

>>x=3.2

x =3.2000

>>exp(x) ans =24.5325

>> d(1)=true d =1 >> d(2)=false d = 1 0 >>a=1.5

a = 1.5000

>> a<5 ans = 1 Boolean Expression

Matrix >>a=[1 2 3 4] a =1 2 3 4 >>a=[1 2;3 4] a = 1 2 3 4 >>a=1:10 a =1 2 3 4 5 6 7 8 9 10

>> a=1:10 a = 1 2 3 4 5 6 7 8 9 10 >> a=1:2:10 a = 1 3 5 7 9 >>10:-2:1 ans =10 8 6 4 2

>>I = eye(3), x = [8; -4; 1], I*x I = 1 0 0 0 1 0 0 0 1 x = 8 -4 1 ans = 8 4 1

>> a=rand(4,4) a = 0.8147 0.6324 0.9575 0.9572

0.9058 0.0975 0.9649 0.4854

0.1270 0.2785 0.1576 0.8003

0.9134 0.5469 0.9706 0.1419

>>a(1,2) ans =0.6324

>> a(1,[1,2]) ans = 0.8147 0.6324

>> a(1,:) ans = 0.8147 0.6324 0.9575 0.9572

>> a(1,2:end) ans =0.6324 0.9575 0.9572

a = 0.8147 0.6324 0.9575 0.9572

0.9058 0.0975 0.9649 0.4854

0.1270 0.2785 0.1576 0.8003

0.9134 0.5469 0.9706 0.1419

>> a(1,2:end-1)=[10,10] a = 0.8147 10.0000 10.0000 0.9572

0.9058 0.0975 0.9649 0.4854

0.1270 0.2785 0.1576 0.8003

0.9134 0.5469 0.9706 0.1419

>> a(1:2,:)=[] a = 0.1270 0.2785 0.1576 0.8003

0.9134 0.5469 0.9706 0.1419

a = 0.8147 0.6324 0.9575 0.9572

0.9058 0.0975 0.9649 0.4854

0.1270 0.2785 0.1576 0.8003

0.9134 0.5469 0.9706 0.1419

>> a(5) ans = 0.1576

>> a(:) ans = 0.1270

0.9134

0.2785

0.5469

0.1576

0.9706

0.8003

0.1419

a = 0.1270 0.2785 0.1576 0.8003

0.9134 0.5469 0.9706 0.1419

>> a<0.5

ans = 1 1 1 0 0 0 0 1 >> a(a<0.5)= -1 a = -1.0000 -1.0000 -1.0000 0.8003

0.9134 0.5469 0.9706 -1.0000

>> ind=find(a<0.5) ind = 1 3 5 8 a = 0.1270 0.2785 0.1576 0.8003

0.9134 0.5469 0.9706 0.1419

• • • • • • [r,c]=find(a<0.5) r = 1 1 1 2 • • • • • c = 1 2 3 4 a= 0.1270 0.2785 0.1576 0.8003

0.9134 0.5469 0.9706 0.1419

>> numel(a) ans = 8 >> a=rand(2,2) a = 0.4218 0.7922

0.9157 0.9595

>> b=[a,a] b = 0.4218 0.7922 0.4218 0.7922

0.9157 0.9595 0.9157 0.9595

0.1270 0.2785 0.1576 0.8003

0.9134 0.5469 0.9706 0.1419

>> b=[a;a] b = 0.4218 0.7922

0.9157 0.9595

0.4218 0.7922

0.9157 0.9595

>> a=1.5

a =1.5000

>> if a<5 disp('it is within the range') end it is within the range b = 0.4218 0.7922 0.4218 0.7922

0.9157 0.9595 0.9157 0.9595

Character constant

>> name='john' name = john >>[name 'smith'] ans =Johnsmith >>name(1:2) ans = jo >> k=1 % index with which to construct a sring k = 1 >> str=['ring' num2str(k)] str = ring1

>> car.year=2010 ans = 2010 >> car.color=‘red’ ans =red >> car.name=‘maruthi’ ans =maruthi

Structure

>>car=struct('year','2010','color','red','name','maruthi') car = year: '2010‘ color: 'red‘ name: 'maruthi‘ >>cars=[car;car] cars = 2x1 struct array with fields: year color name

>> cars(2).name='feat' cars = 2x1 struct array with fields: year color name >>cars.name

ans = maruthi ans = feat

>> cars(1).name,cars(2).name

ans = maruthi ans = Feat

Cell Array

mycell={1 2 3;'test' [1;2] false} mycell = [1] [ 2] [3] 'test' [2x1 double] [0]

>> mycell={1, 2,'orange',true} mycell = [1] [2] 'orange' [1] >>y=mycell(1,1) y = [1] >> y=mycell(1,2) y = [2]

>> y=mycell(1,3) y = 'orange‘ >>y=mycell(1,4) y = [1] >>class(y) ans = Cell

>>y=mycell{1,3} y =orange >>class(y) ans = char

>> mycell{3:4} ans = Orange ans =1 >> newcell={mycell{3:4}} newcell = 'orange' [1]

• if • switch • for • while

Flow Control

statement statement loops loops if A > B 'greater' elseif A < B 'less' else 'equal' end • continue • break statement statement for x = 1:10 r(x) = x; end

>> x = pi*(-1:3), round(x) %Round to nearest integer x = -3.1416 0 3.1416 6.2832 9.4248

ans = -3 0 >> fix(x) ans = -3 >> floor(x) 0 ans = -4 0 3 6 9 3 3 6 6 9 9 %Round toward zero % rounds against negative infinity

>> ceil(x) ans = -3 0 >> sign(x), 4 % Round towards positive infinity 7 10 1 if the corresponding element of X is greater than zero 0 if the corresponding element of X equals zero -1 if the corresponding element of X is less than zero ans = -1 0 1 1 1

Plotting the figure

>>t=0:0.05:0.5

>>y=sin(2*pi*t) y = 0 0.5878 0.9511 0.9511 0.5878 0.0000

>>plot(t,y) 1 0.9

0.8

0.7

0.6

0.5

0.4

0.3

0.2

0.1

0 0 0.05

0.1

0.15

0.2

0.25

0.3

0.35

0.4

0.45

0.5

Random Numbers

x=rand(100,1); stem(x); hist(x,100)

Line Styles & Colours The default is to plot solid lines. A solid white line is produced by >> plot(x,y,'w-') The third argument is a string whose rst character species the colour(optional) and the second the line style. The options for colours and styles are: Colours Line Styles y yellow . point m magenta o circle c cyan x x-mark r red + plus g green - solid b blue * star w white : dotted k black -. dashdot -- dashed

• • • • • • • x=1:5 x = 1 2 3 4 5 >> y=log(x) y = 0 0.6931 1.0986 1.3863 1.6094

>> plot(x,y) • plot(x,y,'*') 1.8

1.6

1.4

1.2

1 0.8

0.6

0.4

0.2

0 1 1.5

2 2.5

3 3.5

4 4.5

5 0.6

0.4

0.2

0 1 1.8

1.6

1.4

1.2

1 0.8

1.5

2 2.5

3 3.5

4 4.5

5

>>t=[12 23] t =12 23 >> y=[1,5] y =1 5 >> plot(t,y) >> plot(t,y,'r-') 5 4.5

4 3.5

3 2.5

2 1.5

1 12 14 16 18 20 22 24

Loops

1 >>x = -1:.05:1; >> for n = 1:2:8 0 -1 -1 1 subplot(4,2,n), plot(x,sin(n*pi*x)) subplot(4,2,n+1), plot(x,cos(n*pi*x)) 0 end -1 -1 1 0 draw sin(n*pi*x)and cos sin(n*pi*x)for n = 1; 3; 5; 7 alongside each other.

-1 -1 1 0 We may use any legal variable name as the \loop counter" -1 -1 (n in the above examples) and it can be made to run through all of the values in a given vector (1:8 and 1:2:8 in the examples).

We may also use for loops of the type -0.5

-0.5

-0.5

-0.5

0 0.5

0 0.5

0 0.5

0 0.5

1 1 1 1 -1 -1 1 0 -1 -1 1 0 -1 -1 1 0 -1 -1 1 0 -0.5

-0.5

-0.5

-0.5

0 0.5

0 0 0 0.5

0.5

0.5

1 1 1 1

Matlab Graphics

x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x=0:2\pi') ylabel('Sine of x') title('Plot of the Sine Function')

Multiple Graphs

t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); plot(t,y1,t,y2) grid on

t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); subplot(2,2,1) plot(t,y1) subplot(2,2,2) plot(t,y2)

Multiple Plots

• x=1:10; • y=1:10; • Z=x'*y; • surf(x,y,z); 100 80 60 40 20 0 10 5 0 0 2 4 6 8 10

>> [X,Y] = meshgrid(2:.2:4, 1:.2:3); >> Z = (X-3).^2-(Y-2).^2; >> mesh(X,Y,Z) >> title('Saddle'), xlabel('x'),ylabel('y') 1 0.5

0 -0.5

-1 3 2.5

2 y 1.5

1 2 Saddle 2.5

x 3 3.5

4

>>t=0:0.1:0.5

t =0 0.1000 0.2000 0.3000 0.4000 0.5000

>>y=sin(2*pi*t) y =0 0.5878 0.9511 0.9511 0.5878 0.0000

>>w=y'*y; >>surf(w) 1 0.8

0.6

0.4

0.2

0 6 4 2 0 1 2 3 4 5 6

Coin Tosses

• Simulate the outcomes of 100 fair coin tosses x=rand(100,1); p=sum(x<0.5)/100 p = 0.5400

• Simulate the outcomes of 1000 fair coin tosses x=rand(1000,1); p=sum(x<0.5)/1000 p =

Coin Tosses

• Simulate the outcomes of 1000 biased coin tosses with p[Head]=0.4

x=rand(1000,1); p=sum(x<0.4)/1000 p = 0.4160