Module 1
Module 1
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.
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
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] -----> 22 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.
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
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
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.
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.
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𝑥 =
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.
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