0% found this document useful (0 votes)
12 views

Module 1

Uploaded by

Sumukh Kini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Module 1

Uploaded by

Sumukh Kini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

MODULE -1 Signals & Systems

INTRODUCTION TO MATLAB
MATLAB is high-level languages and mathematical programming environments for:
 Interactive mathematical calculations
 Visualization: availability of graphical tools (2D and 3D colour graphics)
 Programming, algorithm development & Easy to use : gives integrated
editor/debugger to write, modify, debug the program,
 Numerical computation: linear algebra, optimization, control, statistics, signal and
image processing, etc.
 Auto dimensioning- eliminates data type declarations
 Various In- Built Functions
 m-file --- two types : m- function file and m script files
1. m- Function file : In- Built Functions
 User can use these functions to perform a task
 It is ASCII files containing the algorithms
 Algorithms on specific topics such as Control Systems, Signal
Processing, Neural etwork, Fuzzy Logic, Communication, etc.
 User can create their own function files using appropriate commands

2. m - script files
 Editing / coding text pad (user can code /edit various lines here, using
various MATLAB commands / m- function files)
 It is convenient to modify and save a script m-file each time if a change
of parameters is desired.
Function m-files provide a sensible alternative. Unlike script m-files, function m-
files can accept input arguments as well as return outputs.
Basics of MATLAB workspace
How to run MATLAB
 Open to the Windows operating environment.
 Create a new folder on the desktop and rename it with your register number and
open
that folder.
 Double-click the ‘MATLAB’ icon; this will route the terminal to the MATLAB
Command Window automatically, with a MATLAB prompt.
 There are generally 4 sub-windows. They are Editor, Command Window, Current
Folder, Variables
 One can undock these widgets and separate those windows OR delete unrequired
ones.
These are generally variable, file list, etc.
 If command window is selected, >> prompt is shown. One may type commands
here
one by one. OR
 If the Editor window is selected, a blank is shown. Select the HOME menu in the
top left corner and select New Script.
 Save it with a convenient name. This will be the script m-file. Select the EDITOR
menu in the top left corner and select Save As. While saving make sure that one
should
save the script file in the folder created on the desktop for later easy access.
1
 This is a window to edit /write MATLAB code/codes. Then it can be compiled and
used
for running the program code.
 By using the appropriate commands, one can invoke various activities / built-in
functions / create variables, etc.

 Creating m-script files or editor window -- second method


 Inside the opened folder (your register no.), create a new file by right clicking and
selecting new document and empty document. This will create a new file.
 Rename the file with some filename with extension .m E.g. :- filename1.m {do
not rename with only numbers or only letters. Preferred, letters followed by numbers.
This is to avoid the any clash built-in function file with the created m-script file.}
Example : If poly.m is used to save one script file, then whenever any built in
commands are used which internally uses function poly will have a confusion in
execution. It causes error which very difficult to debug.
 Type the required sequence of MATLAB Commands and save it.
 To run/execute the m script file created, click the MATLAB Command Window and
type
only filename which you have renamed {without .m extension} OR use Run button
in
top menu in Editor.
 When m-script file runs, MATLAB executes the commands in the order they are
written
just as if they were typed in the Workspace.
 To exit click top right corner close button.
 You can also use Ctrl C to come out half the way of the program execution, or infinite
loops, if any.
NOTE : DO NOT GIVE THE script FILENAME WHICH IS A BUILTIN m_file.
Example: %ex1.m
clear, clc,
% To compute inverse of a matrix and Determinant
A = [1 2 9; 4 4 6;7 8 7];
disp(‘The inverse and determinant of matrix A is:’)
A_inverse = inv(A)
A_determinant = det(A)
 Various commands helpful to work with MATLAB in workspace are:
who whos clc clear load save path pause help lookfor edit etc.
HELP OR DOC
If we know the name of an MATLAB function and would like to know how to use it, we
write the following command in the command window: > help > help sin e.t.c.
If we want to look for a keyword, which we don’t know as a built in function, say
inverse, we write: > lookfor inverse e.t.c.
It convenient to use ‘help’ command, for quick reference.
 Familiarize with the following useful commands in the MATLAB workspace

2
>>who lists variables in workspace
>>whos lists variables and their sizes
>>clc clear command window
>>clear clear workspace
>>save session1 a b to save variables a & b of the workspace in session1
>>load session1 to load variables to workspace
>> save myfile.dat a b saves a,b in myfile.dat
>>disp (‘I have successfully completed MATLAB basics’)
>> R = input ('How many apples') gives the user the prompt in the text string
and then waits for input from the keyboard.
 Saving the contents of the variable to dat file:
There are two approaches :
First approach: Let a and b are variables
> save myfile.dat a b ---- > saves a,b in myfile.dat --- > This will save the
contents of the variables in binary form, which manually cannot be modified .
One can see the file contents by opening it in notepad/text environment but cannot
comprehend anything from it.
Second approach:
> save myfile.dat a b -ascii ---- > saves a,b in myfile.dat --- > This will save
the contents of the variables in ascii form, which can be manually modified .
One can see the file contents by opening it in notepad/text environment and
add/delete/append the values.

>load myfile.dat a b ------ > is used for loading the contents to workspace. Here,
the contets of a and b are loaded into a new variable, myfile.

MATLAB as Calculator
>>pi^pi-10;
>>cos(pi/4);
√ √
>>ans*ans; the result will be × = ½ because the first output is eliminated,
only last output is kept in the form of ans

Elementary Matrix Operations (Quick Reference)


Entering Arrays/Matrices with real elements (use of : operator)
M = [first:increment:last] -----> Array with elements
M = linspace(first,last,n) -----> Array with n elements linearly spaced
M = logspace(first,last,n) -----> Array with n elements logarithmically spaced

To Enter an Array
>>M = 0:1:5 = [0, 1, 2, 3, 4, 5] >>M = linspace(1,5,3) = [1,3,5]
>>M = logspace(1,5,3) = [10,1000,100000] >>M = [(2+4/5), sqrt(2.8),
4.2,7]
To Enter a matrix with real elements

3
>>M = [1 2 3; 4 5 6] >>M = [1,2,3; sqrt(2.8),5.2,5e-
2]
Vectorization
First approach:
>> s = [ ]; %initializes all values of vector s to zero
>> for n = 0:5 %note that the index must be integer
>> s(n+1) = sin(0.2*pi*0.2); %since we want values of s every 0.2 seconds we
must
multiply n by 0.2. note also that for n = 0 the
variable
becomes s(1) and this because the array in
MATLAB
always starts counting columns from 1.
>> end
Second approach:
>> n = 0:0.2:1
>> s = sin(0.2*pi*n) % the result of these two commands gives the signal s (sine
function) at times (value of n) 0, 0.2, 0.4, 0.6, 0.4, 1
This approach is preferable since MATLAB executes faster with the vectorization
approach rather than the for-loop approach.
Entering matrices with complex elements
a = 2 + 5i ------> complex number
A = [5+3j 7+8j; 9+2j 6+5j] -----> 22 complex matrix
A = [1 2;3 4] + i*[5 6;7 8]
Matrix generation functions
>> [ ] Empty matrix >>zeros(3) 3×3 matrix of zeros
>>ones(2) 2×2 matrix of ones >>eye(3) identity matrix of size
3
>>rand(3) 3×3 matrix of random numbers

Examples

4
Given Matrix A = [1 2 9; 4 4 6;7 8 7] B = [3 6 9;2 4 6;1 2 3],
Accessing submatices >>A(1:2,2:3); >>A(1,:); >>B(:,2)
Concatenating two matrices >>D=[A B]; >>E=[A;B]
Adding a row >>A(4,:)=[1 1 0]
Deleting a column >>B(:,2)=[ ]
>>A(3) accesses the third element of A.
>>A([1 2 3]) is the first three elements of A. So is
>>A([SQRT(2), SQRT(3), 4*ATAN(1)]).
If A has N components, >>A(N:-1:1) reverses them.
>>A([1,5],:) = A([5,1],:) interchanges rows 1 and 5 of A.

MATRIX Manipulations / Functions /operations


Given Matrix A (square)
A’ -----> Transpose of a matrix
inv(A) -----> inverse of a matrix
det(A) -----> determinant of a matrix
A*A -----> matrix multiplication
diag(A) -----> diagonal of a matrix
triu(A) , tril(A) , lu(A), eig(A), eigs(A), etc.
Given an array A=[1 5 3 10 2 0 4 6], sort in ascending order. >>sort(A)

OPERATORS
Arithmetic operators
+ Plus. - Minus.
* Matrix multiplication. .* Array multiplication
^ Matrix power .^ Array power
\ Backslash or left division / Slash or right division
./ Array division
Array operations [ Element by Element operation] [dot operators]
Matrix operations preceded by a period . (dot) indicates array operation.
Element by element operations require vectors to have the same dimensions. Eg.
------> .* ./ .^
A = [1 2 3]; B = [2 4 6];
C = A .* B = [1*2, 2*4, 3*6] ; C = A ./ B = [1/2, 2/4, 3/6] ;
C = A.^2 = [1, 4, 9];

Relational operators
< less than <= Less than or equal to
> greater than >= Greater than or equal to
== equal ~= Not equal
Logical operators
& AND | OR ~ NOT XOR Exclusive OR

Simple math functions


sin, cos, tan, asin, acos, atan, sinh, cosh log, log10, exp, sqrt …

5
Permanent variables
ANS Default result variable
EPS 2.22 x 10-16 user definable
PI  pre-calculated
INF 1/0
NAN Not A Number Eg: 0/0; inf/inf

Special characters
( ) Parentheses are used to indicate precedence in arithmetic expressions and to
arguments of functions in the usual way.
[ ] Brackets used to assign arrays/matrices
, Element separator ; Row, line delimiter
% Comments ! Exclamation point
' Transpose, quote = Assignment
: Colon ... Continuation
Logical functions...
EXIST Check if variables or functions exist.
ANY True if any element of a vector is true.
ALL True if all elements of a vector are true.
FIND Find indices of the non-zero elements.
ISNAN True for Not-A-Number.
ISINF True for infinite elements.
FINITE True for finite elements.
ISEMPTY True for empty matrices.
ISREAL True for matrix of only real elements.
ISSPARSE True if matrix is sparse.
ISSTR True for text string.
ISGLOBAL True for global variables
Display formats...
>>format Default. Same as SHORT
>>format short Scaled fixed point format with 5 digits. Eg. 1.3333
>>format long Scaled fixed point format with 15 digits. Eg. 1.33333333333333

Graphics
plot(x,y) Linear plotting -----> plots vector y versus vector x
plot(Y) Plots the columns of Y versus their index
plot(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) combines the plots
fplot(‘function’,limits,linespecifiers) ----> plots a function with y = f(x)
Eg: x = linspace (a ,2*pi, 30); y = sin(x); plot(x,y)

Include modifications
title text grid xlabel gtext legend ylabel ginput

Customising plot axes using axis command

6
axis([ xmin xmax ymin ymax] )

Set the maximum and minimum values of axes using specified values.
To autoscale: use min or max –inf or inf respectively
 H = subplot(m,n,p), or subplot(m,n,p), breaks the Figure window into an m-by-n
matrix of small axes, selects the p-th axes for the current plot
 Hold : to have multiple figures in the same window
 Plotting with Logarithmic axis : loglog , semilogx(x,y), semilogy(x,y)
 Plotting with special graphics : bar, barh, stairs, stem, hist, polar etc.

Creating Function Files – User Defined Functions :


 Function files are created and edited, like script file, in the Editor/Debugger Window.
Synthetically, a function m-file is identical to a script m-file except for the first line. The
general form of the first line (called “function definition line” is:
function[output1, output2,…] = filename(input1, input2,…). OR
function[output arguments] = filename(input arguments). OR
function[a, b,…] = multiply1(x, y,…).

 Function body contains the computer program (code) that actually performs the
computations
 Save the function file with a name that is identical to the function name in the function
definition line with extension .m Eg :- multiply1.m
 User defined functions are in the same way as a built in function. To use function file,
the directory where it was saved must be in the current directory.
 In function body help comments can also be added for future references, in the second
line of the function file.
 All the variables in the function file are local. To assign and use global variables, global
MATLAB command can be used.

Flow control (Loops) (Conditional Jumps)


CE -----> Conditional Expression
1. FOR loop 2. IF statement 3. WHILE loop 4. Switch SE
for k = F:I:L if CE1 while CE case ….
…. …. …. case
end else if CE2 end …..

7
…. end
Else
….
end
end
 Nested loops and Nested conditional statements are allowed.
 Indefinite loop may occur if there is a mistake in the usage of loops. In such cases
Control+C
OR Control +Break key may be used.
 break and continue commands:
o when inside loop (for and while), break command terminates the execution
of the whole loop.
o when outside a loop (for and while), break command terminates the
execution of the file.
o continue command can be used inside a loop to stop the present pass and start
the next pass in the looping process. It omits the remaining commands in the
loop.

Polynomials
 Polynomial is represented by a row vector of its coefficients in descending order
x4- 12x3 + 25x + 116 as p = [1 –12 0 25 116]
 Roots of the polynomial -----> r =roots(p)
 The polynomial can be got from the roots as p = poly(r)
 Value of a Polynomial : polyval(p,x) x : number, or a variable that has an
assigned value can be array or matrix
 Multiplication of polynomials: c = conv(p,q)
 Division of polynomials: c = deconv(p,q)
 Addition : two polynomials can be added (or subtracted) by adding the vectors of the
coefficients. If the polynomials are not of the same order, the shorter vector has to be
modified by adding zeros(called padding)
 Partial fraction expansion : the function residue performs a partial fraction
expansion F(s) = p / q
[rr , pp , k ] = residue (p, q)
F (s) = k + r1 / (x – p1)+ r2 / (x – p2) + …
 Derivatives of the polynomials: pd = polyder(p)
 Derivatives of a product of two polynomials: pdp= polyder(p,q)
 Derivatives of a quotient of two polynomials: [k,n] = polyder(p,q)

8
MATLAB Basics Exercises

MATLAB as a calculator:
1) Define the variables x and z as x=9.6, and z=8.1, then evaluate:

a) 𝑥𝑧 − b) + c) d) 𝑙𝑜𝑔|𝑥 − 𝑥 |
2) Verify the trigonometric identities by substituting and calculating each side of the
equation with x = π/5
𝑐𝑜𝑠 = ; 𝑐𝑜𝑠 = ; 𝑡𝑎𝑛2𝑥 =

Entering array / Matrices:

3) Write single line code to perform the following: (avoid using for loop)

4).

5) Using the zeros and ones commands as well as write single line command to create a
3×5 matrix in which the first, second and fifth columns are 0’s and the third and fourth
columns are 1’s.

Matrix /subscription/concatenation:
6) Create a 5×7 matrix in which the first row are the numbers 1 2 3 4 5 6 7, the second row
are the numbers 8 9 10 11 12 13 14, and so on. From this matrix create a new 3×4 matrix
that is made from rows 2 through 4, and columns 3 through 6 of the first matrix.

9
7) Construct a matrix A of size 39 × 75 whose number fields vary from 0 to 10
a. Write a single line code/ command to plot number fields of 5th row vs. number
fields of 32nd row using matrix A
b. Write a single line code/ command to plot number fields of 15th row vs. number
fields of 4th and 6th columns (suitably choosing the number of number fields),
using matrix A
c. Write a single line code/ command to construct matrix B whose size is 4 × 26
considering the number fields of 1st row (75 number fields) and the number fields
of 66th column (39 number fields) of A matrix.
d. Write a single line code/ command in to construct matrix B whose size is 25 × 29
considering the number fields of all columns corresponding to 8th row to 10th row
(suitable number fields) and number fields of all rows corresponding to 46th
column to 50th column (suitable number fields) of A matrix.

8) Construct a matrix of A of size 5 × 6 whose number fields vary from 0 to 10.


Construct a matrix of B of size 2 × 45 whose number fields vary from 0 to 10.
Write a single line code/ command to construct matrix C whose size is 8 × 15
considering all the number fields of matrices A and B (i.e using matrices A and B).

TRY TO CREATE m - SCRIPT FILES FOR SOLVING THE BELOW EXERCISES

Matrix Manipulations / Functions /operations


9) and 10)

11)

10
Graphics
12) Make two separate plots of the function f(x) = 0.6x5-5x3+9x+2; one plot for -4≤x≤4
and one for -2.7≤x≤2.7. Also plot the same using fplot.
13)

14) ,15)

11

You might also like