Lecture 2: Functions, Plots & Symbolic Math Instructor: Hamze Msheik LEBANESE AMERICAN UNIVERSITY...

Post on 17-Dec-2015

217 views 1 download

Transcript of Lecture 2: Functions, Plots & Symbolic Math Instructor: Hamze Msheik LEBANESE AMERICAN UNIVERSITY...

Lecture 2: Functions, Plots & Symbolic Math

Instructor: Hamze Msheik

LEBANESE AMERICAN UNIVERSITYSchool of Engineering

Department of Electrical and Computer Engineering

Fall 2014

Function Files

Creating MATLAB Functions

Simple programming in MATLAB

Introduction

3

Script files are used to write programs, to save and to run them using MATLAB commands.

Script files contain list of MATLAB commands. Script are saved in “filename.m” Select File menu in the MATLAB toolbar:

File>New>M-file The Editor window will open.

Creating Script Files

4

Commands in M-files are executed in the order they are listed.

Script files can be edited and executed many times. The program is automatically saved when Run button

is pressed.

Run command

Breakpoints

5

Breakpoints can be placed in script files for debugging.

A breakpoint can be set for every line. Place the cursor on the desired line. Press F12 or choose Debug>Set/Clear Breakpoint

from Editor toolbar.

Program stops and Workspace variables are updated once the program reaches a breakpoint press continue button to resume the program

Example of M-file

6

Function files

7

MATLAB has its own set of built-in and toolbox functions Example: sin, exp, rand, plot…

User can write his own function and executes it.

Function files are written using the Editor Window.

A function has a name, can have input arguments and output arguments.

The first line in Function files has the following format: function [out1,…,outm] =function-name(arg1,

…,argn) [out1,…,outm] is an array that returns m

variables (arg1,…,argn) is a list of n arguments that

the function takes.

Function Files

8

function[out1,…,outm]=function-name(arg1,…,argn)

Function-name It’s the function name. The M-file should have the same name as

function-name M-files that contain functions are saved as

Function-name.m In order to call a user defined function,

function-name.m should exist in the Current Directory.

Example of function files

9

Let’s define a function that transforms the polar coordinates into their corresponding Cartesian coordinates.

Let’s name the function pol_to_cart This function has 2 input arguments:

r and theta This function has 2 output arguments:

x and y

Example of function files

10

Calling User defined functions

11

>> [x,y]=pol_to_cart(1,pi/6)x = 0.86603y = 0.5User defined functions can run in Command

Window, or in Script Files or in other Function Files.

Function Overloading

12

The behavior of a function can be modified depending on the number of input and output arguments.

Commands: nargin: Number of Input arguments

nargout: Number of Output arguments Example:

function [P]=integral(t,x,flag)if nargin==2

dt=t(2)-t(1); P=sum(x)*dt;

elseif nargin==3 dt=t(2)-t(1); P=cumsum(x).*dt;

end

Saving Data

13

MATLAB uses its own platform independent file format for saving data files. Files have a “.mat” extension save is used to save variables from the workspace

to a named file (by default: matlab.mat if no filename is given) save filename – saves entire workspace to

filename.mat save var1 var2 … filename – saves named variables

to filename.mat By default save overwrites an existing file of the

same name, use –append to append data to an existing file Variables of the same name are always overwritten!!! save var1 var2 … filename -append

Data is recovered using load command load filename – loads entire .mat file load filename var1 var2 … - loads named vars

Prompting for User input

14

The input function can be used to prompt the user for numeric or string input.

x = input(‘Enter a value for x’);YourName = input(‘Enter your

name’, ‘s’);

MatLab Programming

15

Program Control Statements:

Conditional Control (if, switch) Loop Control (for, while, continue,

break) Error Control (try, catch) Program Termination (return)

Conditional Control (if statement)

16

clear;x=-2;y=10;if(x<0) angle=180+atand(y/x)else angle=atand(y/x)end

Loop Control (For loop)

17

Loop Expression Format:for index = start:increment:end statementsend

Example:for n = 2:size(x,2) x(n) = 2 * x(n - 1);end

The command break exits a loop

Comparison of break and return

18

break is used to escape the current loop. return is used to escape the current function.

Remark: an infinite loop can be broken by typing “Ctrl+C”

Plotting in MATLAB

Plot Function

Subplot function

Plotting Properties

Plotting

20

MATLAB is used extensively to plot graphs. Different parameters can be modified in

MATLAB figures: Number of subplots in a figure Scale (i.e. Linear or Logarithmic) Grid, colors, labels and legends.

Consider the plotting example: t=0:0.001:20; f=exp(-t).*sin(2*pi*10*t); plot(t,f), grid

Note: t and f have the same size

Plot command

21

Plotting a function

22

The Figure can be edited and labeled such that:

ylabel('F(t)')xlabel('t')title('F(t)=e^{-t}.sin(20\pit)')axis([0,2,-1,1]) % axis([xmin, xmax, ymin,

ymax])legend('F(t)')

Plotting a function

23

Plotting 2 curves on the same graph

24

Use the help command to get more information on the plot command.

t=0:0.0001:3;f=exp(-t).*sin(2*pi*10*t);g=cos(2*pi*t);plot(t,f,'r‚)holdplot(t,g,'b--')legend('f(t)','g(t)')

t=0:0.0001:3;f=exp(-t).*sin(2*pi*10*t);g=cos(2*pi*t);plot(t,f,'r',t,g,'b--')legend('f(t)','g(t)')

2 ways

Plotting 2 curves on the same graph

25

Plotting 2 curves in 1 graph window

26

t=0:1e-4:3;f=exp(-t).*sin(2*pi*10*t);g=cos(2*pi*t);subplot(2,1,1),plot(t,f),gridsubplot(2,1,2),plot(t,g),grid

subplot(M,N,n) creates an array of M-by-N graphs in a figure window, where n is the number of a selected graph in the array.

Plotting 2 curves in 1 graph window

27

Plotting 4 curves in 1 graph window

28

t=0:1e-4:3;f= exp(-t).*sin(2*pi*10*t);g= cos(2*pi*t);y= tan(2*pi*t);w= sinc(t); subplot(2,2,1),plot(t, f),gridsubplot(2,2,2),plot(t, g),gridsubplot(2,2,3),plot(t, w),gridsubplot(2,2,4),plot(t, y),grid

Plotting 4 curves in 1 graph

29

Plotting curves in different graph windows

30

To open a new window and to plot a curve, we use the command: figure

Example:

t=0:0.1:10;y1=sin(2*pi*t);y2=exp(-0.5*t)*sin(2*pi*t);plot(t,y1)figure,plot(t,y2)

In this way, the first graph stays in the first window, and a new window opens and displays the second graph.

Plotting curves in different windows

31

Semi-logarithmic plot

32

Semi-logarithmic plot is the same as plot, except a logarithmic (with base 10) scale is used for the Y-axis.

Semi-logarithmic plots are used extensively in communication systems to plot the error probability versus the Signal-to-Noise ratio (SNR) Referred to as Bit Error Rate (BER) graphs. Such plots are very useful in comparing

corresponding communication systems

See also: semilogx, loglog

Semi-logarithmic plot - Example

33

Consider the below example, where two types of signaling are to be compared:

SNR=[-200:10:-110];Pe1=[0.498 0.442 0.378 0.221 0.109 0.0254 0.0124 0.00213 0.00118

0.000175];Pe2=[0.748 0.582 0.378 0.121 0.059 0.0154 0.0064 0.00113

0.000568 0.0000175];

semilogy(SNR, Pe1,'ro-',SNR,Pe2,'b^-'),gridtitle('Symbol Error Probability')xlabel('SNR(dB)')ylabel('P_S')legend('Binary Signaling','4-ary Signaling')

Semi-logarithmic plot - Example

34

Multidimensional Functions

35

Consider the function f(x, y):

f(x,y) is defined over the range: -2<x<2 -3<y<3

To define the domain of definition of this multidimensional function, we use the command: ndgrid

22

),( yxxeyxf

Multidimensional Functions

36

Plotting f(x,y) is done by:

x=-2:0.2:2;y=-3:0.2:3;[X,Y]=ndgrid(x,y);f=X.*exp(-X.^2-Y.^2);mesh(X,Y,f)

Use the help command to further understand ndgrid and mesh commands.

It plots in a 3-Dimensional Space the points whose coordinates are in matrices X, Y and f.

Multidimensional Functions

37

-2-1.5

-1-0.5

00.5

11.5

2

-3

-2

-1

0

1

2

3

-0.5

-0.4

-0.3

-0.2

-0.1

0

0.1

0.2

0.3

0.4

0.5

xy

f

Symbolic Math Toolbox

Symbolic Math

Mathematical Operations Using Symbolic Math

Symbolic Math

39

It defines variables that don’t have necessarily a defined scalar or numerical value.

Symbolic objects can be used as independent variables. For Example we can use the command syms such that:

syms x y z Therefore x, y and z are three Symbolic Objects.

A symbolic object can be: A variable with no pre-assigned numerical value.

Ex: syms x y t A number.

Ex: a=sym(2) An expression made of symbolic variable/numbers.

Ex: syms x y; z=sqrt(x+y)

A symbolic expression is a mathematical expression made of one or several symbolic objects.

Creating Symbolic Objects

40

We use the commands sym and syms to create symbolic objects.

To create one Symbolic Object: a=sym(2)

a has a symbolic-numerical value b=sym(‘gamma’)

b has a symbolic-string value.

To create multiple symbolic objects: syms x y z

Symbolic v.s Numerical

41

Symbolic objects: a and b a=sym(1); b=sym(2); f=a/b f = ½

Numerical objects: A and B:A=1;B=2;F=A/BF =0.500

Symbolic to Numeric

42

Some symbolic expressions can have numerical values resulting from numerical operations.

To convert from symbolic to numerical objects, we use the command double(S).

Example:

a=sym(3);b=1/ab = 1/3B=double(b)B = 0.33333

findsym command

43

Used to find and enumerate symbolic variables present in an expression.

Command Syntax: findsym(S)

Displays all symbolic variables found in S, in alphabetical order.

findsym(S,n) Displays the first n symbolic variables found in S, in

default order Default order Start from x (first symbol in the expression) and

list the others in the order of their closeness to x.

subs command

44

To substitute a variable in a symbolic expression we use the command subs. Consider the following example: syms x y; f=2*x+log(y); subs(f,x,2); ans = 4+log(y) subs(f,[x y],[2 1]) ans = 4

The Factor command: sym x

G=-1/2*exp(-x)*cos(x)-1/2*exp(-x)*sin(x)

factor(G)

ans = -1/2*exp(-x)*(cos(x)+sin(x)) See also: expand, simplify, pretty.

Solving equations (Symbolic)

45

Solving algebraic equations. Example (2 equations, 2 unknowns)

[x y]=solve('2*x+a*y-1=0','b*x+2*y=0') x =-2/(b*a-4) y =1/(b*a-4)*b

Solving Differential equations: ‘Dn’ represents the nth order derivative operator Consider the Example: x’’+a2x=0, IC: x(0)=1,

x’(0)=1 x = dsolve('D2x+a^2*x=0','x(0)=1, Dx(0)=1')

x = 1/a*sin(a*t)+cos(a*t)

Calculating Derivatives (Symbolic)

46

Partial Derivatives Consider the function given by:

f = sin(x^2+y)

Partial derivative w.r.t. x f_x=diff(f,x) f_x =2*cos(x^2+y)*x

2nd Partial derivative w.r.t. x f2_x=diff(f,x,2) f2_x = -4*sin(x^2+y)*x^2+2*cos(x^2+y)

Calculating Integrals (Symbolic)

47

Integration Consider the function given by:

f=sin(x)*exp(-x)

Definite integral (i.e. Integrate f(x) over the range [0,2]) F=int(f,x,0,2) F =-1/2*exp(-2)*cos(2)-1/2*sin(2)*exp(-2)+1/2

Indefinite Integral G=int(f,x) G =-1/2*exp(-x)*cos(x)-1/2*sin(x)*exp(-x)

Inline function

48

Used for multivariable expressions. Returns a function that takes several

arguments. As an example:

D=inline('2*x*y+sin(x)','x','y') D = Inline function: D(x,y) = 2*x*y+sin(x)

D(1,2) ans = 4.8415

Linear Math

Expressing Polynomials in MATLAB

Polynomials

50

Polynomials are represented in MATLAB using row vectors.

Polynomial coefficients are ordered by descending power.

For example: F(x)=x4+2x-1 F=[1 0 0 2 -1]

Polynomial roots

51

To get the roots of a polynomial expression, we use the command roots.

Example: Finding the roots of F(x)=x3-x+2 (i.e. Solving

P(x)=0) F=[1 0 -1 2] roots(F)

ans = -1.5214 0.76069 + 0.85787i 0.76069 - 0.85787i

F(x) has one real and two complex conjugate solutions

Polynomial coefficients

52

If we want to form a polynomial having specific roots, we use the command poly.

Example: Form a polynomial having the following roots: 2, 1-j, 1+jpoly([2;1-j;1+j])ans = 1 -4 6 -4

The corresponding polynomial is: F(x)=x3-4x2+6x-4

Note: that the roots are stored in a column vector, and the polynomial coefficients are stored in a row vector.

Evaluating Polynomials

53

To evaluate polynomials for a specific value of the variable we use the command polyval.

Example: Calculate F(2). F = 1 0 -1 2

polyval(F,2)ans = 8

Multiplication of Polynomials (Convolving)

54

We use the command conv to multiply two polynomials.

Example: Given P(x)=x3+2x-1 and Q(x)=x2-1, calculate

P(x)*Q(x).P=[1 0 2 -1];Q=[1 0 -1];conv(P,Q)ans = 1 0 1 -1 -2 1

Then: P(x)*Q(x)=x5+x3-x2-2x+1

Division of Polynomials (Deconvolving)

55

The output of the division of two polynomials is represented in the following expression:

A(x)/B(x) = q(x) + r(x)/B(x)

q(x) is the quotient of the polynomial division and r(x) is the remainder.

To divide two polynomials, we use the command deconv.

Division of Polynomials

56

Consider A(x)=x4+2x2-1 and B(x)=x3+x. Find A(x)/B(x):

A=[1 0 0 2 -1];B=[1 0 1 0];[q,r]=deconv(A,B)q = 1 0r = 0 0 -1 2 -1

Where q(x) = x and r(x)=-x2+2x-1, the final answer, will look like:

xx

xxx

xB

xA

3

2 12

Polynomials operations

57

Polynomial derivative: Use the command polyder

Partial Fraction Expansion: Use the command residue to get the partial

fraction expansion.

Elaborate on these commands on your own.