Presentation is loading. Please wait.

Presentation is loading. Please wait.

SFU Winter 2004 MATLAB PROGRAMMING MATLAB Tutorial Dr GUNASEKARAN THANGAVEL Lecturer & Program Co-ordinator Electronics & Telecommunication Engineering.

Similar presentations


Presentation on theme: "SFU Winter 2004 MATLAB PROGRAMMING MATLAB Tutorial Dr GUNASEKARAN THANGAVEL Lecturer & Program Co-ordinator Electronics & Telecommunication Engineering."— Presentation transcript:

1 SFU Winter 2004 MATLAB PROGRAMMING MATLAB Tutorial Dr GUNASEKARAN THANGAVEL Lecturer & Program Co-ordinator Electronics & Telecommunication Engineering EEE Section Department of Engineering Higher College of Technology, Muscat. T.Gunasekaran Handout ENSC320

2 Alternatives Complements
SFU Winter 2004 MATLAB Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra routines (Lapak/Linpak) Commercialized 1984 by The Mathworks Since then heavily extended (defacto-standard) Alternatives Complements Matrix-X Maple (symbolic) Octave (free; GNU) Mathematica (symbolic) Lyme (free; Palm) T.Gunasekaran Handout ENSC320

3 SFU Winter 2004 MATLAB The MATLAB environment is command oriented somewhat like UNIX. A prompt appears on the screen and a MATLAB statement can be entered. When the <ENTER> 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 next prompt. The following slide is the text from a MATLAB screen. T.Gunasekaran Handout ENSC320

4 SFU Winter 2004 MATLAB To get started, type one of these commands: helpwin, helpdesk, or demo » a=5; » b=a/2 b = 2.5000 T.Gunasekaran Handout ENSC320

5 MATLAB Variable Names Variable names ARE case sensitive
SFU Winter 2004 MATLAB Variable Names Variable names ARE case sensitive Variable names can contain up to 63 characters (as of MATLAB 6.5 and newer) Variable names must start with a letter followed by letters, digits, and underscores. T.Gunasekaran Handout ENSC320

6 MATLAB Special Variables
SFU Winter 2004 MATLAB Special Variables ans Default variable name for results pi Value of  inf NaN Not a number e.g. 0/0 i and j i = j = eps Smallest incremental number realmin The smallest usable positive real number realmax The largest usable positive real number T.Gunasekaran Handout ENSC320

7 MATLAB Math & Assignment Operators
SFU Winter 2004 MATLAB Math & Assignment Operators Power ^ or .^ a^b or a.^b Multiplication * or .* a*b or a.*b Division / or ./ a/b or a./b or \ or .\ b\a or b.\a NOTE: /8 = 8\56 - (unary) + (unary) Addition a + b Subtraction a - b Assignment = a = b (assign b to a) T.Gunasekaran Handout ENSC320

8 Other MATLAB symbols >> prompt
SFU Winter 2004 Other MATLAB symbols >> prompt . . . continue statement on next line , separate statements and data % start comment which ends at end of line ; (1) suppress output (2) used as a row separator in a matrix : specify range T.Gunasekaran Handout ENSC320

9 MATLAB Help System Search for appropriate function
SFU Winter 2004 MATLAB Help System Search for appropriate function >> lookfor keyword Rapid help with syntax and function definition >> help function An advanced hyperlinked help system is launched by >> helpdesk Complete manuals as PDF files T.Gunasekaran Handout ENSC320

10 SFU Winter 2004 MATLAB Matrices MATLAB treats all variables as matrices. For our purposes a matrix can be thought of as an array, in fact, that is how it is stored. Vectors are special forms of matrices and contain only one row OR one column. Scalars are matrices with only one row AND one column T.Gunasekaran Handout ENSC320

11 SFU Winter 2004 MATLAB Matrices A matrix with only one row AND one column is a scalar. A scalar can be created in MATLAB as follows: » a_value=23 a_value = 23 T.Gunasekaran Handout ENSC320

12 SFU Winter 2004 MATLAB Matrices A matrix with only one row is called a row vector. A row vector can be created in MATLAB as follows (note the commas): » rowvec = [12 , 14 , 63] rowvec = T.Gunasekaran Handout ENSC320

13 SFU Winter 2004 MATLAB Matrices A matrix with only one column is called a column vector. A column vector can be created in MATLAB as follows (note the semicolons): » colvec = [13 ; 45 ; -2] colvec = 13 45 -2 T.Gunasekaran Handout ENSC320

14 SFU Winter 2004 MATLAB Matrices A matrix can be created in MATLAB as follows (note the commas AND semicolons): » matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9] matrix = T.Gunasekaran Handout ENSC320

15 Extracting a Sub-Matrix
SFU Winter 2004 Extracting a Sub-Matrix A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names of both matrices and the rows and columns to extract. The syntax is: sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ; where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the beginning and ending columns to be extracted to make the new matrix. T.Gunasekaran Handout ENSC320

16 SFU Winter 2004 MATLAB Matrices A column vector can be extracted from a matrix. As an example we create a matrix below: » matrix=[1,2,3;4,5,6;7,8,9] matrix = Here we extract column 2 of the matrix and make a column vector: » col_two=matrix( : , 2) col_two = 2 5 8 T.Gunasekaran Handout ENSC320

17 SFU Winter 2004 MATLAB Matrices A row vector can be extracted from a matrix. As an example we create a matrix below: » matrix=[1,2,3;4,5,6;7,8,9] matrix = Here we extract row 2 of the matrix and make a row vector. Note that the 2:2 specifies the second row and the 1:3 specifies which columns of the row. » rowvec=matrix(2 : 2 , 1 : 3) rowvec = T.Gunasekaran Handout ENSC320

18 Reading Data from files
SFU Winter 2004 Reading Data from files MATLAB supports reading an entire file and creating a matrix of the data with one statement. >> load mydata.dat; % loads file into matrix. % The matrix may be a scalar, a vector, or a % matrix with multiple rows and columns. The % matrix will be named mydata. >> size (mydata) % size will return the number % of rows and number of % columns in the matrix >> length (myvector) % length will return the total % no. of elements in myvector T.Gunasekaran Handout ENSC320

19 SFU Winter 2004 Plotting with MATLAB MATLAB will plot one vector vs. another. The first one will be treated as the abscissa (or x) vector and the second as the ordinate (or y) vector. The vectors have to be the same length. MATLAB will also plot a vector vs. its own index. The index will be treated as the abscissa vector. Given a vector “time” and a vector “dist” we could say: >> plot (time, dist) % plotting versus time >> plot (dist) % plotting versus index T.Gunasekaran Handout ENSC320

20 SFU Winter 2004 Plotting with MATLAB There are commands in MATLAB to "annotate" a plot to put on axis labels, titles, and legends. For example: >> % To put a label on the axes we would use: >> xlabel ('X-axis label') >> ylabel ('Y-axis label') >> % To put a title on the plot, we would use: >> title ('Title of my plot') T.Gunasekaran Handout ENSC320

21 SFU Winter 2004 Plotting with MATLAB Vectors may be extracted from matrices. Normally, we wish to plot one column vs. another. If we have a matrix “mydata” with two columns, we can obtain the columns as a vectors with the assignments as follows: >> first_vector = mydata ( : , 1) ; % First column >> second_vector = mydata ( : , 2) ; % Second one >> % and we can plot the data >> plot ( first_vector , second_vector ) T.Gunasekaran Handout ENSC320

22 Some Useful MATLAB commands
SFU Winter 2004 Some Useful MATLAB commands who List known variables whos List known variables plus their size help Ex: >> help sqrt Help on using sqrt lookfor Ex: >> lookfor sqrt Search for keyword sqrt in m-files what Ex:>> what a: List MATLAB files in a: clear Clear all variables from work space clear x y Clear variables x and y from work space clc Clear the command window T.Gunasekaran Handout ENSC320

23 Some Useful MATLAB commands
SFU Winter 2004 Some Useful MATLAB commands what List all m-files in current directory dir List all files in current directory 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 T.Gunasekaran Handout ENSC320

24 MATLAB Relational Operators
SFU Winter 2004 MATLAB Relational Operators MATLAB supports six relational operators. Less Than < Less Than or Equal <= Greater Than > Greater Than or Equal >= Equal To == Not Equal To ~= T.Gunasekaran Handout ENSC320

25 MATLAB Logical Operators
SFU Winter 2004 MATLAB Logical Operators MATLAB supports three logical operators. not ~ % highest precedence and & % equal precedence with or or | % equal precedence with and T.Gunasekaran Handout ENSC320

26 MATLAB Logical Functions
SFU Winter 2004 MATLAB Logical Functions MATLAB also supports some logical functions. xor (exclusive or) Ex: xor (a, b) Where a and b are logical expressions. The xor operator evaluates to true if and only if one expression is true and the other is false. True is returned as 1, false as 0. any (x) returns 1 if any element of x is nonzero all (x) returns 1 if all elements of x are nonzero isnan (x) returns 1 at each NaN in x isinf (x) returns 1 at each infinity in x finite (x) returns 1 at each finite value in x T.Gunasekaran Handout ENSC320

27 MATLAB Display formats
SFU Winter 2004 MATLAB Display formats MATLAB supports 8 formats for outputting numerical results. format long 16 digits format short e 5 digits plus exponent format long e 16 digits plus exponent format hex hexadecimal format bank two decimal digits format + positive, negative or zero format rat rational number (215/6) format short default display T.Gunasekaran Handout ENSC320

28 Matlab Selection Structures
SFU Winter 2004 Matlab Selection Structures An if - elseif - else structure in MATLAB. Note that elseif is one word. if expression1 % is true % execute these commands elseif expression2 % is true else % the default end T.Gunasekaran Handout ENSC320

29 MATLAB Repetition Structures
SFU Winter 2004 MATLAB Repetition Structures A for loop in MATLAB for x = array for x = 1: 0.5 : 10 % execute these commands end A while loop in MATLAB while expression while x <= 10 % execute these commands T.Gunasekaran Handout ENSC320

30 Scalar - Matrix Addition
SFU Winter 2004 Scalar - Matrix Addition » a=3; » b=[1, 2, 3;4, 5, 6] b = » c= b+a % Add a to each element of b c = T.Gunasekaran Handout ENSC320

31 Scalar - Matrix Subtraction
SFU Winter 2004 Scalar - Matrix Subtraction » a=3; » b=[1, 2, 3;4, 5, 6] b = » c = b - a %Subtract a from each element of b c = T.Gunasekaran Handout ENSC320

32 Scalar - Matrix Multiplication
SFU Winter 2004 Scalar - Matrix Multiplication » a=3; » b=[1, 2, 3; 4, 5, 6] b = » c = a * b % Multiply each element of b by a c = T.Gunasekaran Handout ENSC320

33 Scalar - Matrix Division
SFU Winter 2004 Scalar - Matrix Division » a=3; » b=[1, 2, 3; 4, 5, 6] b = » c = b / a % Divide each element of b by a c = T.Gunasekaran Handout ENSC320

34 MATLAB Toolbox More than 60 toolboxes!
SFU Winter 2004 MATLAB Toolbox MATLAB has a number of add-on software modules, called toolbox , that perform more specialized computations. Signal & Image Processing  Signal Processing- Image Processing Communications - System Identification - Wavelet  Filter Design     Control Design  Control System - Fuzzy Logic - Robust Control - µ-Analysis and Synthesis - LMI Control Model Predictive Control More than 60 toolboxes! Toolboxes T.Gunasekaran Handout ENSC320

35 MATLAB Toolbox MATLAB has many toolboxes:
SFU Winter 2004 MATLAB Toolbox MATLAB has many toolboxes: Control toolbox is one of the important toolbox in MATLAB. RLC Circuit Response, Gain and Phase Margins, Notch Filter Discrete, PID and ... T.Gunasekaran Handout ENSC320

36 SFU Winter 2004 MATLAB Demo Demonstrations are invaluable since they give an indication of the MATLAB capabilities. A comprehensive set are available by typing the command >>demo in MATLAB prompt. T.Gunasekaran Handout ENSC320

37 SFU Winter 2004 MATLAB demos, RLC Circuit Response demos Handout ENSC320

38 Sample - RLC Band Stop Filter
SFU Winter 2004 Sample - RLC Band Stop Filter Consider the circuit below: + R + L VO Vi _ C _ Matlab sample bandstop filter. The transfer function for VO/Vi can be expressed as follows: T.Gunasekaran Handout ENSC320

39 SFU Winter 2004 RLC Band Stop Filter This is of the form of a band stop filter. We see we have complex zeros on the jw axis located From the characteristic equation we see we have two poles. The poles an essentially be placed anywhere in the left half of the s-plane. We see that they will be to the left of the zeros on the jw axis. We now consider an example on how to use this information. T.Gunasekaran Handout ENSC320

40 SFU Winter 2004 RLC Band Stop Filter Design a band stop filter with a center frequency of rad/sec and having poles at 100 rad/sec and 3000 rad/sec. The transfer function is: We now write a Matlab program to simulate this transfer function. T.Gunasekaran Handout ENSC320

41 RLC Band Stop Filter num = [1 0 300000]; den = [1 3100 300000];
SFU Winter 2004 RLC Band Stop Filter num = [ ]; den = [ ]; w = 1 : 5 : 10000; Bode(num,den,w) T.Gunasekaran Handout ENSC320

42 SFU Winter 2004 MATLAB - Reference: A Partial List of On-Line Matlab Tutorials and Matlab Books Getting started with Matlab A quick reference to some of the key features of Matlab Matlab tutorial, with lots of links to other tutorials Control Tutorial for Matlab A Practical Introduction to Matlab Matlab Tutorial Information from UNH T.Gunasekaran Handout ENSC320

43 SFU Winter 2004 The END T.Gunasekaran Handout ENSC320

44 COMPLEX DATA AND CHARACTER DATA
COMPLEX NUMBERS: c = a + ib , i = sqrt (-1) Complex numbers are used in Electrical engg. ac voltage, current and impedance representation Matlab uses rectangular coordinates to represent complex numbers. T.Gunasekaran

45 Complex variables Created automatically, when a complex value is assigned to a variable. Example: >> c1 = 4 + i * 3 c1 = i T.Gunasekaran

46 isreal (array) returns a 0.
The function isreal used to determine whether a given array is real or complex. If any element of an array has an imaginary component, then the array is complex isreal (array) returns a 0. T.Gunasekaran

47 USING COMPLEX NUMBERS WITH RELATIONAL OPERATORS
To compare two complex numbers == is used, to see if the two numbers are equal. To compare two complex numbers ~= is used, to see if the two numbers are not equal to each other. Example >> c1 = 4 + i*3; >> c2 = 4 – i*3; >> c1 = c2 % produces 0 as output >> c1 ~= c2 % produces 1 as output T.Gunasekaran

48 Comparisons with < , >, >=, or <= do not produce the expected results. (only real parts of the numbers are compared) Total magnitude can be calculated as follows, >> abs(c) = sqrt(a^2 + b^2); T.Gunasekaran

49 Converts data from complex data type to real (double) data type.
COMPLEX FUNCTIONS 3 categories of complex functions: 1. Type Conversion Functions 2. Absolute value and Angle Functions 3. Mathematical Functions Type Conversion Functions Converts data from complex data type to real (double) data type. real and imag T.Gunasekaran

50 Absolute value and Angle Functions
Convert a complex numbers to its polar representation. Function abs(c) calculates the absolute value of a complex number. >> abs(c) = sqrt(a^2 + b^2) Function angle(c) calculates the angle of a complex number. >> angle(c) = atan2 (imag (c), real (c) ) Producing the answer in the range –π to +π. T.Gunasekaran

51 MATHEMATICAL FUNCTIONS
Exponential, logarithms, trigonometric functions and square roots. Sin, cos, log, sqrt …. T.Gunasekaran

52 Functions that support complex numbers
conj (c) computes the complex conjugate of a number c. real (c) returns the real portion of the complex number imag (c) returns the imaginary portion of the complex number isreal (c) returns 1 if no element of array c has an imaginary Component abs(c) returns the magnitude of the complex number. T.Gunasekaran

53 y(t) = e-0.2t (cos t + i sin t) Using conventional plot command:
Plotting Complex Data Example y(t) = e-0.2t (cos t + i sin t) Using conventional plot command: Ignores imag. Data and plots real value w.r. to time >> t = 0:pi/20:4*pi; >> y = exp(-0.2*t) .* (cos (t) + i * sin (t)); >> plot(t,y); >> title ('\bfplot of complex functions VS time'); >> Xlabel ('\bf\itt'); >> ylabel ('\bf\ity(t)'); T.Gunasekaran

54 Plotting both real and imaginary values w.r.to Time
>> t = 0:pi/20:4*pi; >> y = exp(-0.2*t) .* (cos (t) + i * sin (t)); >> plot (t,real(y),’b-’); >> hold on; >> plot(t, imag (y),’r-’); >> title(‘\bfplot of complex functions VS Time’); >> xlabel (‘\bf\itt’); >> ylabel (‘bf\ity(t)’); >> legend (‘real’, ‘imaginary’); >> hold off; T.Gunasekaran

55 Plot of Real part VS Imaginary part
>> t = 0:pi/20:4*pi; >> y = exp(-0.2*t) .* (cos (t) + i * sin (t)); >> plot(y,’b-’); >> title ('\bfplot of complex functions '); >> Xlabel ('\bfreal part'); >> ylabel ('\bfimaginary part'); T.Gunasekaran

56 >> y = exp(-0.2*t) .* (cos (t) + i * sin (t));
Polar Plot >> t = 0:pi/20:4*pi; >> y = exp(-0.2*t) .* (cos (t) + i * sin (t)); >> polar (angle(y),abs(y)); >> title ('\bfplot of complex function '); T.Gunasekaran

57 A matlab string is an array of type char.
STRING FUNCTIONS A matlab string is an array of type char. Each character is stored in two bytes of memory. A character variable is automatically created when a string is assigned to it. Example >> str = ‘this is a test‘; >> whos str Name Size Bytes Class str x char array Grand total is 14 elements using 28 bytes T.Gunasekaran

58 ischar It is a special function, used to check for character arrays.
ischar(str)  returns with 1, if the given variable is a character array. If it is not the ischar(str) returns with false value. >> ischar(str) ans = 1 >> x=42; >> ischar(x) T.Gunasekaran

59 STRING CONVERSION FUNCTIONS character to double
Variables can be converted from the character data type to the double data type using double function. >> str ='this is a test'; >> x = double (str) x = T.Gunasekaran

60 STRING CONVERSION FUNCTIONS double to character
Using char (x) function. >> x = double (str) x = >> z = char (x) z = this is a test T.Gunasekaran

61 Creating Two-Dimensional Character Arrays
Each row of 2-D array must have exactly same length. If not, the character array is invalid and will produce an error. Example >> name= ['Gunasekaran T'; 'Lecturer/ECE']; ??? Error using ==> vertcat All rows in the bracketed expression must have the same number of columns. T.Gunasekaran

62 To produce 2-D character arrays with char function
>> name=char('T.Gunasekaran','Lecturer/ECE') name = T.Gunasekaran Lecturer/ECE T.Gunasekaran

63 2-D character Array creation
Also created by using strvcat >> name=strvcat('T.Gunasekaran','Lecturer/ECE') name = T.Gunasekaran Lecturer/ECE Removing any extra blanks from a string Using deblank (strname(line no)) T.Gunasekaran

64 Concatenating Strings
Function strcat concatenates 2 or more strings horizontally, ignoring any trailing blanks but preserving blanks within the strings. Example >> result = strcat ('string ','string 2') result = string 1string 2 T.Gunasekaran

65 >> result = strvcat('long string 1', 'string 2') result =
Concatenates 2 or more strings vertically, automatically padding the strings to make a valid 2-D array. Example >> result = strvcat('long string 1', 'string 2') result = long string 1 string 2 T.Gunasekaran

66 Two strings or parts of two strings can be compared for equality.
COMPARING STRINGS Two strings or parts of two strings can be compared for equality. Two individual strings can be compared for equality. Strings can be examined to determine whether each character is a letter or white space. T.Gunasekaran

67 COMPARING STRINGS FOR EQUALITY
Strcmp Determines if two strings are identical. Strcmpi Determines if two strings are identical and ignoring case. Strncmp Determines if the first ‘n’ characters of two strings are identical . Strncmpi Determines if the first ‘n’ characters of two strings are identical and ignoring case. T.Gunasekaran

68 >> str1= ‘hello’; >> str2 = ‘Hello’;
Examples >> str1= ‘hello’; >> str2 = ‘Hello’; >> str3 = ‘help’; >> c = strcmp (str1,str2) C = >> strcmpi (str1, str2) 1 T.Gunasekaran

69 >> str1= ‘hello’; >> str2 = ‘Hello’;
Examples >> str1= ‘hello’; >> str2 = ‘Hello’; >> str3 = ‘help’; >> c = strncmp (str1,str3,2) % any value up to 3 C = 1 T.Gunasekaran

70 Comparing Individual Characters for Equality and Inequality
>> a = ‘fate’; >> b = ‘cake’; >> result = a == b result = > , <, <=, >=, == and ~= compares the ASCII values of the corresponding characters. T.Gunasekaran

71 Categorizing Characters within a String
Isletter Determines if a character is a letter. isspace Determines if a character is whitespace. Example: >> mystring = ‘guna ece2005z’ ; >> a = Isletter (mystring) a= T.Gunasekaran

72 STRING TO NUMBER CONVERSION AND VICE-VERSA
int2str num2str mat2str str2double str2num BASE NUMBER CONVERSIONS hex2num hex2dec dec2hex Bin2dec dec2bin base2dec dec2base T.Gunasekaran

73 ADDITIONAL 2-D PLOTS bar (x,y) vertical bar plot
barh (x,y) Horizontal bar plot compass (x,y) polar plot with an arrow from ori pie (x) pie plot stairs (x,y) stair plot stem (x,y) vertical (discrete) plot from x- axis ezplot (fun) function plot Fun= sin (x) / x ezplot (fun, [xmin xmax]) ezplot (fun, [xmin xmax] , figure ) T.Gunasekaran

74 COMMUNICATION TOOLBOX
Signal Sources Signal Analysis Functions Source Coding Error-Control Coding Lower-Level Functions for Error-Control Coding ANALOG and DIGITAL Modulation/Demodulation Lower-Level Functions for Special Filters Channel Functions Bit Interleaving/Deinterleaving Performance evaluation Equalizers T.Gunasekaran

75 Signal Sources randerr - Generate bit error patterns.
randint Generate matrix of uniformly distributed random integers. randsrc Generate random matrix using prescribed alphabet. wgn Generate white Gaussian noise. T.Gunasekaran

76 Signal Analysis Functions
biterr Compute number of bit errors and bit error rate. eyediagram - Generate an eye diagram. scatterplot - Generate a scatter plot. symerr Compute number of symbol errors and symbol error rate. T.Gunasekaran

77 arithdeco - Decode binary code using arithmetic decoding.
Source Coding arithdeco Decode binary code using arithmetic decoding. arithenco - Encode a sequence of symbols using arithmetic coding. compand Source code mu-law or A-law compressor or expander. dpcmdeco Decode using differential pulse code modulation. dpcmenco Encode using differential pulse code modulation. T.Gunasekaran

78 dpcmopt - Optimize differential pulse code modulation parameters.
Source Coding dpcmopt Optimize differential pulse code modulation parameters. lloyds Optimize quantization parameters using the Lloyd algorithm. quantiz Produce a quantization index and a quantized output value. T.Gunasekaran

79 convenc - Convolutionally encode binary data.
Error-Control Coding. bchpoly Produce parameters or generator polynomial for binary BCH code. convenc Convolutionally encode binary data. cyclgen Produce parity-check and generator matrices for cyclic code. cyclpoly Produce generator polynomials for a cyclic code. decode Block decoder. encode Block encoder. T.Gunasekaran

80 gen2par - Convert between parity-check and generator matrices.
Error-Control Coding. gen2par Convert between parity-check and generator matrices. gfweight Calculate the minimum distance of a linear block code. hammgen Produce parity-check and generator matrices for Hamming code. rsdec Reed-Solomon decoder. rsenc Reed-Solomon encoder. rsdecof Decode an ASCII file that was encoded using Reed-Solomon code. T.Gunasekaran

81 rsencof - Encode an ASCII file using Reed- Solomon code.
Error-Control Coding. rsencof Encode an ASCII file using Reed- Solomon code. rsgenpoly - Produce Reed-Solomon code generator polynomial. syndtable - Produce syndrome decoding table. vitdec Convolutionally decode binary data using the Viterbi algorithm. T.Gunasekaran

82 Lower-Level Functions for Error-Control Coding
bchdeco BCH decoder. bchenco BCH encoder. Special Filters hank2sys Convert a Hankel matrix to a linear system model. hilbiir Hilbert transform IIR filter design. rcosflt Filter the input signal using a raised cosine filter. rcosine Design raised cosine filter. T.Gunasekaran

83 Modulation/Demodulation
ademod Analog passband demodulator. ademodce Analog baseband demodulator. amod Analog passband modulator. amodce Analog baseband modulator. apkconst Plot a combined circular ASK-PSK signal constellation. ddemod Digital passband demodulator. ddemodce Digital baseband demodulator. T.Gunasekaran

84 Modulation/Demodulation
demodmap Demap a digital message from a demodulated signal. dmod Digital passband modulator. dmodce Digital baseband modulator. modmap Map a digital signal to an analog signal. qaskdeco Demap a message from a QASK square signal constellation. qaskenco Map a message to a QASK square signal ` constellation. T.Gunasekaran

85 Lower-Level Functions for Special Filters
rcosfir Design a raised cosine FIR filter. rcosiir Design a raised cosine IIR filter. Channel Functions awgn Add white Gaussian noise to a signal. T.Gunasekaran

86 bi2de - Convert binary vectors to decimal numbers.
Utilities bi2de Convert binary vectors to decimal numbers. de2bi Convert decimal numbers to binary numbers. erf Error function. erfc Complementary error function. istrellis - Check if the input is a valid trellis structure. marcumq Generalized Marcum Q function. T.Gunasekaran

87 oct2dec - Convert octal numbers to decimal numbers.
mask2shift - Convert mask vector to shift for a shift register configuration. oct2dec Convert octal numbers to decimal numbers. poly2trellis - Convert convolutional code polynomial to trellis description. shift2mask - Convert shift to mask vector for a shift register configuration. vec2mat Convert a vector into a matrix. T.Gunasekaran

88 >> help commdemos
Communications Toolbox Demonstrations. Demos. basicsimdemo Basic communications link simulation demonstration. gfdemo Galois fields. rcosdemo Demonstration of raised cosine functions. scattereyedemo Demonstration of eye diagram and scatter plot functions. vitsimdemo Convolutional encoder and Viterbi decoder demonstration. Documentation examples. commgettingstarted - Simple communications example. simbasebandex Baseband QPSK simulation example. simpassbandex Passband QPSK simulation example. See also COMM, SIGDEMOS. T.Gunasekaran

89 RANDERR Generate bit error patterns
OUT = RANDERR(M) generates an M-by-M binary matrix with exactly one "1" randomly placed in each row. OUT = RANDERR(M,N) generates an M-by-N binary matrix with exactly one "1" randomly placed in each row. OUT = RANDERR(M,N,ERRORS) generates an M-by-N binary matrix, with the number of "1"s in any given row determined by ERRORS. T.Gunasekaran

90 OUT = RANDERR(M,N,ERRORS,STATE) resets the state of RAND to STATE.
This function can be useful for testing error-control coding. Examples: » out = randerr(2,5) » out = randerr(2,5,2) out = out = » out = randerr(2,5,[1 3]) » out = randerr(2,5,[1 3; ]) See also RAND, RANDSRC, RANDINT. T.Gunasekaran

91 ANALOG MODULATION - AM >>Fs = 8000; % Sampling rate is 8000 samples per second. >>Fc = 300; % Carrier frequency in Hz >>t = [0:.1*Fs]'/Fs; % Sampling times for .1 second >>x = sin(20*pi*t); % Representation of the signal >>y = ammod(x,Fc,Fs); % Modulate x to produce y. >>figure; >>subplot(2,1,1); plot(t,x); % Plot x on top. >>subplot(2,1,2); plot(t,y); % Plot y below. T.Gunasekaran

92 Amplitude Modulation T.Gunasekaran

93 ANALOG MODULATION- PM % Prepare to sample a signal for two seconds,
% at a rate of 100 samples per second. Fs = 100; % Sampling rate t = [0:2*Fs+1]'/Fs; % Time points for sampling % Create the signal, a sum of sinusoids. x = sin(2*pi*t) + sin(4*pi*t); Fc = 10; % Carrier frequency in modulation phasedev = pi/2; % Phase deviation for phase modulation y = pmmod(x,Fc,Fs,phasedev); % Modulate. y = awgn(y,10,'measured',103); % Add noise. z = pmdemod(y,Fc,Fs,phasedev); % Demodulate. % Plot the original and recovered signals. figure; plot(t,x,'k-',t,z,'g-'); legend('Original signal','Recovered signal'); T.Gunasekaran

94 PHASE MODULATION AND DEMODULATION
T.Gunasekaran

95 Digital Modulation and Demodulation
Computing the Symbol Error Rate This example generates a random digital signal, modulates it, and adds noise. Then it creates a scatter plot, demodulates the noisy signal, and computes the symbol error rate. T.Gunasekaran

96 MODULATING A RANDOM SIGNAL
% Create a random digital message M = 16; % Alphabet size x = randint(5000,1,M); % Message signal % Use 16-QAM modulation. y = qammod(x,M); % Transmit signal through an AWGN channel. ynoisy = awgn(y,15,'measured'); % Create scatter plot from noisy data. scatterplot(ynoisy); % Demodulate to recover the message. z = qamdemod(ynoisy,M); % Check symbol error rate. [num,rt]= symerr(x,z) T.Gunasekaran

97 OUTPUT num = 87 rt = 0.0174 T.Gunasekaran

98 Plotting Signal Constellations
To plot the signal constellation associated with a modulation process, follow these steps: If the alphabet size for the modulation process is M, then create the signal [0:M-1]. This signal represents all possible inputs to the modulator. Use the appropriate modulation function to modulate this signal. If desired, scale the output. The result is the set of all points of the signal constellation. Apply the scatter plot function to the modulated output to create a plot. T.Gunasekaran

99 Constellation for 16-PSK
The code below plots a PSK constellation having 16 points. M = 16; x = [0:M-1]; scatterplot(pskmod(x,M)); T.Gunasekaran

100 Constellation for 32-PSK
M = 32; x = [0:M-1]; y = qammod(x,M); scale = modnorm(y,'peakpow',1); y = scale*y; % Scale the constellation. scatterplot(y); % Plot the scaled constellation. % Include text annotations that number the points. hold on; % Make sure the annotations go in the same figure. for jj=1:length(y) text(real(y(jj)),imag(y(jj)),[' ' num2str(jj-1)]); end hold off; T.Gunasekaran

101 CHANNELS – FADING CHANNEL
Power of a Faded Signal c = rayleighchan(1/10000,100); sig = j*ones(2000,1); % Signal y = filter(c,sig); % Pass signal through channel. c % Display all properties of the channel object. % Plot power of faded signal, versus sample number. plot(20*log10(abs(y))) T.Gunasekaran

102 OUTPUT c = ChannelType: 'Rayleigh' InputSamplePeriod: 1.0000e-004
MaxDopplerShift: 100 PathDelays: 0 AvgPathGaindB: 0 NormalizePathGains: 1 PathGains: i ChannelFilterDelay: 0 ResetBeforeFiltering: 1 NumSamplesProcessed: 2000 T.Gunasekaran

103 OUTPUT CONTD., c = ChannelType: 'Rayleigh'
InputSamplePeriod: e-004 MaxDopplerShift: 100 PathDelays: 0 AvgPathGaindB: 0 NormalizePathGains: 1 PathGains: i ChannelFilterDelay: 0 ResetBeforeFiltering: 1 NumSamplesProcessed: 2000 T.Gunasekaran

104 IMAGE PROCESSING TOOLBOX
Deblurring Image Enhancement Image Registration Image Transformations Morphology – Analysis and Segmentation T.Gunasekaran

105 Deblurring Images Using the Blind Deconvolution Algorithm
Used effectively when no information about the distortion (blurring and noise) is known. The algorithm restores the image and the point-spread function (PSF) simultaneously. Steps to be followed to obtain Deblurring Step 1: Read in Images Step 2: Simulate a blur Step 3: Restore the Blurred Image Using PSFs of Various Sizes Step 4: Improving the Restoration Step 5: Using Additional Constraints on the PSF Restoration T.Gunasekaran

106 The example reads in an intensity image.
Step 1: Read in Images The example reads in an intensity image. The deconvblind function can handle arrays of any dimension. >> I = imread('cameraman.tif'); >> figure;imshow(I);title('Original Image'); T.Gunasekaran

107 IMREAD - Read image from graphics file
A = IMREAD(FILENAME,FMT) reads the image in FILENAME into A. If the file contains a grayscale intensity image, A is a two-dimensional array. If the file contains a true color (RGB) image, A is a three-dimensional (M-by-N-by-3) array. FILENAME is a string that specifies the name of the graphics file, and FMT is a string that specifies the format of the file. The file must be in the current directory or in a directory on the MATLAB path. If IMREAD cannot find a file named FILENAME, it looks for a file named FILENAME.FMT. T.Gunasekaran

108 Simulate a real-life image that could be blurred.
Simulate a blur Simulate a real-life image that could be blurred. e.g., due to camera motion or lack of focus. The example simulates the blur by convolving a Gaussian filter with the true image (using imfilter). The Gaussian filter then represents a point-spread function, PSF. >>PSF = fspecial('gaussian',7,10); >>Blurred = imfilter(I,PSF,'symmetric','conv'); >>figure;imshow(Blurred);title('Blurred Image'); T.Gunasekaran

109 Restore the Blurred Image Using PSFs of Various Sizes
To illustrate the importance of knowing the size of the true PSF, this example performs three restorations. Each time the PSF reconstruction starts from a uniform array--an array of ones. The first restoration, J1 and P1, uses an undersized array, UNDERPSF, for an initial guess of the PSF. The size of the UNDERPSF array is 4 pixels shorter in each dimension than the true PSF. >> UNDERPSF = ones(size(PSF)-4); >>[J1 P1] = deconvblind(Blurred,UNDERPSF); >>figure;imshow(J1);title('Deblurring with Undersized PSF'); T.Gunasekaran

110 The second restoration
J2 and P2, uses an array of ones, OVERPSF, for an initial PSF that is 4 pixels longer in each dimension than the true PSF. >>OVERPSF = padarray(UNDERPSF, [4 4],'replicate','both'); >>[J2 P2] = deconvblind(Blurred,OVERPSF); >>figure;imshow(J2);title('Deblurring with Oversized PSF'); T.Gunasekaran

111 >>INITPSF = padarray(UNDERPSF,[2 2],'replicate','both');
The third restoration J3 and P3, uses an array of ones, INITPSF, for an initial PSF that is exactly of the same size as the true PSF. >>INITPSF = padarray(UNDERPSF,[2 2],'replicate','both'); >>[J3 P3] = deconvblind(Blurred,INITPSF); >>figure;imshow(J3);title('Deblurring with INITPSF'); T.Gunasekaran

112 Analyzing the Restored PSFAll
Three restorations also produce a PSF. The following pictures show how the analysis of the reconstructed PSF might help in guessing the right size for the initial PSF. In the true PSF, a Gaussian filter, the maximum values are at the center (white) and diminish at the borders (black). >>figure; >>subplot(221);imshow(PSF,[],'notruesize'); >>title('True PSF'); T.Gunasekaran

113 Improving the Restoration
The ringing in the restored image, J3, occurs along the areas of sharp intensity contrast in the image and along the image borders. This example shows how to reduce the ringing effect by specifying a weighting function. The algorithm weights each pixel according to the WEIGHT array while restoring the image and the PSF. In our example, we start by finding the "sharp" pixels using the edge function. By trial and error, we determine that a desirable threshold level is 0.3. >> WEIGHT = edge(I,'sobel',.3); % To widen the area, we use imdilate and pass in a structuring element, se. >>se = strel('disk',2); >>WEIGHT = 1-double(imdilate(WEIGHT,se)); % The pixels close to the borders are also assigned the value 0. >>WEIGHT([1:3 end-[0:2]],:) = 0; `>>WEIGHT(:,[1:3 end-[0:2]]) = 0; >>figure;imshow(WEIGHT);title('Weight array'); T.Gunasekaran

114 Using Additional Constraints on the PSF Restoration
The example shows how you can specify additional constraints on the PSF. The function, FUN, below returns a modified PSF array which deconvblind uses for the next iteration. In this example, FUN modifies the PSF by cropping it by P1 and P2 number of pixels in each dimension, and then padding the array back to its original size with zeros. This operation does not change the values in the center of the PSF, but effectively reduces the PSF size by 2*P1 and 2*P2 pixels. >>str = 'padarray(PSF(P1+1:end-P1,P2+1:end-P2),[P1 P2])'; >>FUN = inline(str,'PSF','P1','P2'); The function, FUN, (the inline object name here) followed by its parameters, P1 and P2, are passed into deconvblind last. In this example, the size of the initial PSF, OVERPSF, is 4 pixels larger than the true PSF. Passing P1=2 and P2=2 as input parameters to FUN effectively makes the valuable space in OVERPSF the same size as the true PSF. Therefore, the outcome, JF and PF, is similar to the result of deconvolution with the right sized PSF and no FUN call, J and P, from step 4. >>[JF PF] = deconvblind(Blurred,OVERPSF,30,[],WEIGHT,FUN,2,2); >>figure;imshow(JF);title('Deblurred Image'); T.Gunasekaran

115 SIMULINK Simulink is a tool for modeling, analyzing, and simulating physical and mathematical systems, including those with nonlinear elements and those that make use of continuous and discrete time. As an extension of MATLAB, Simulink adds many features specific to dynamic systems while retaining all of general purpose functionality of MATLAB. T.Gunasekaran

116 Run demos in the following categories
Features Simulink provides many features for powerful and intuitive modeling. Some major features are illustrated in these demonstration models. General Simulink has the ability to simulate a large range of systems, from very simple to extraordinarily complex. The models and demonstrations that you will see in this section include both simple and complex systems. Although the complex systems are nowhere near the limits of what can be done, they hint at the level of sophistication that you can expect. T.Gunasekaran

117 Run demos in the following categories
Automotive Simulink, Stateflow and the Real-Time Workshop represent the industry standard toolset in the automotive field. The models that you will see in this area showcase the use of MathWorks tools in various automotive applications. Aerospace Simulink, Stateflow and the Real-Time Workshop represent the industry standard toolset in the aerospace field. The models that you will see in this area showcase the use of MathWorks tools in various aerospace applications. T.Gunasekaran

118 T.Gunasekaran

119 DISCUSSIONS… T.Gunasekaran


Download ppt "SFU Winter 2004 MATLAB PROGRAMMING MATLAB Tutorial Dr GUNASEKARAN THANGAVEL Lecturer & Program Co-ordinator Electronics & Telecommunication Engineering."

Similar presentations


Ads by Google