Introduction to MATLAB.
What is MATLAB ?
MATLAB is a computer program that combines computation and visualization power that makes
it particularly useful tool for engineers.
MATLAB is an executive program, and a script can be made with a list of MATLAB commands
like other programming language.
MATLAB Stands for MATRIX LABORATORY.
The system was designed to make matrix computation particularly easy.
The MATLAB environment allows the user to:
manage variables
Import and export data
perform calculations
generate plots
develop and manage files for use with MATLAB.
Matlab Environment
Graphic (Figure) Window
Displays plots and graphs
Created in response to graphics commands.
M-file editor/debugger window
Create and edit scripts of commands called M-files.
This is the
work space
which lists
This is the file This is the command window, you can enter all the
display unit in commands and data and results are displayed
which you can here
access files of
system
This is the
command
history
window, it
displays a
log of the
commands
used
Getting Help
Type one of following commands in the command window:
help – lists all the help topic
help topic – provides help for the specified topic
help command – provides help for the specified command
look for keyword – Search all M-files for keyword
Variables:
Variable names
Must start with a letter
May contain only letters, digits, and the underscore
Matlab is case sensitive, i.e. one & OnE are different variables.
Matlab only recognizes the first 31 characters in a variable name.
Assignment statement:
Variable = number;
Variable = expression;
Example:
>> tutorial = 1234;
>> tutorial = 1234
tutorial =
1234
NOTE: When a semi-colon ”;” is placed at the end of each command, the result is not displayed.
Special variables:
ans : default variable name for the result
pi: = 3.1415926…………
eps: = 2.2204e-016, smallest amount by which 2 numbers can differ.
Inf or inf : , infinity
NaN or nan: not-a-number
Commands involving variables:
who: lists the names of defined variables
whos: lists the names and sizes of defined variables
clear: clears all varialbes, reset the default values of special variables.
clear name: clears the variable name
clc: clears the command window
clf: clears the current figure and the graph window.
Vectors:
A row vector in MATLAB can be created by an explicit list, starting with a left bracket, entering
the values separated by spaces (or commas) and closing the vector with a right bracket.
A column vector can be created the same way, and the rows are separated by semicolons.
Example:
>> x = [ 0 0.25*pi 0.5*pi 0.75*pi pi ]
x= x is a row vector
0 0.7854 1.5708 2.3562 3.1416
>> y = [ 0 ; 0.25*pi ; 0.5*pi ; 0.75*pi ; pi ]
y= y is a column vector
0 0.7854
1.5708
2.3562
3.1416
Vector Addressing – A vector element is addressed in MATLAB with an integer index enclosed
in parentheses.
Example:
>> x(2)
ans =
1.5708 2nd elements of vector x
The colon notation may be used to address a block of elements. (start : increment : end) start is
the starting index, increment is the amount to add to each successive index, and end is the ending
index. A shortened format (start : end) may be used if increment is 1.
Example:
>> x(1:3) 1st to 3rd element of x
ans =
0 0.7854 1.5708
NOTE: MATLAB index starts at 1.
Matrices:
A Matrix array is two-dimensional, having both multiple rows and multiple columns, similar to
vector arrays. It begins with [ and end with ] spaces or commas are used to separate elements in
a row semicolon; or enter is used to separate rows.
Example:
>> f = [ 1 2 3; 4 5 6]
f=
123
456
>> h = [ 2 4 6 1 3 5]
h=
246 135
Following are some commands:
Transpose B = A’
Identity Matrix eye(n) returns an n x n identity matrix
eye(m,n) returns an m x n matrix with ones on
the main diagonal and zeros elsewhere
Addition and subtraction C=A+B
C=A–B
Scalar Multiplication B = αA, where α is a scalar.
Matrix Multiplication C = A*B
Matrix Inverse B = inv(A), A must be a square matrix in
this case.
rank (A) returns the rank of the matrixA
Matrix Powers B = A.^2 squares each element in the matrix
C = A * A computes A*A, and A must be a
square matrix.
Determinant det (A), and A must be a square matrix.
A, B, C are matrices, and m, n, α are scalars.
Array Operations:
Scalar-Array Mathematics
For addition, subtraction, multiplication, and division of an array by a scalar simply apply the
operations to all elements of the array.
Example:
>> f = [ 1 2 3 4]
f=
1234
>> g = 2*f – 1 Each element in the array f multiplied by 2, then
subtracted by 1.
g=
1 3 5 7
Element-by-Element Array-Array Mathematics.
Operation Algebraic Form MATLAB
Addition a+b a+b
Subtraction a–b a–b
Multiplication axb a .*b
Division a/b a ./ b
Exponentiatio
ab a.^b
n
Example
>> x = [ 1 2 3 ];
>> y = [ 4 5 6 ];
>> z = x .* y
Each element in x is multiplied by the corresponding element in y.
z= 4 10 18
Solutions to Systems of Linear Equations
Example: A system of 3 linear equation with 3 unknowns
Solution by Matrix Inverse:
Ax = b
A-1.A.x = A-1.b
x = A-1.b
In MATLAB:
>> A = [ 3 2 -1; -1 3 2; 1 -1 -1];
>> b = [ 10; 5; -1];
>> x = inv(A)*b
x=
-2.0000
5.0000
-6.0000
Answer: x1 = -2, x2 = 5, x3 = -6
left division: A\b = b /A
right division: x/y = x / y
Solution by Matrix Division:
The solution to the equation Ax = b can be computed using left division.
In MATLAB:
>> A = [ 3 2 -1; -1 3 2; 1 -1 -1];
>> b = [ 10; 5; -1];
>> x = A\b
x=
-2.0000
5.0000
-6.0000
Answer: x1 = -2, x2 = 5, x3 = -6
Polynomials
MATLAB represents polynomials as row vectors containing coefficients ordered by descending
powers. For example, consider the equation
To enter this polynomial into MATLAB, use
In MATLAB
>>p = [1 0 -2 -5];
Polynomials roots
The roots function calculates the roots of a polynomial:
>>r = roots(p)
r=
2.0946
-1.0473 + 1.1359i
-1.0473 - 1.1359i
By convention, MATLAB stores roots in column vectors.
Polynomial Evaluation
The polyval function evaluates a polynomial at a specified value. To evaluate p at s = 5, use
>>polyval(p,5)
ans =
110
It is also possible to evaluate a polynomial in a matrix sense. In this case the equation becomes
where X is a square matrix and I is the identity matrix.
For example, create a square matrix X and evaluate the polynomial p at X:
>>X = [2 4 5 ; -1 0 3 ; 7 1 5];
>>Y = polyvalm(p,X)
Y=
377 179 439
111 81 136
490 253 639
Introduction to Simulink.
What is Simulink?
Simulink is an environment for simulation and model-based design for dynamic and embedded
systems. It provides an interactive graphical environment and a customizable set of block I
braries that let you design, simulate, implement, and test a variety of time-varying systems,
including communications, controls, signal processing, video processing, and image processing
Simulink offers a quick way of develop your model in contrast to text based-programming
language such as e.g., C.
Start using Simulink:
Open MATLAB and select the Simulink icon in the Toolbar Or type “simulink” in the Command
window
Start simulink
Then the following window appears (Simulink Library Browser)
The Simulink Library Browser is the library where you find all the blocks you may use in
Simulink. Simulink software includes an extensive library of functions commonly used in
modeling a system. These include:
Continuous and discrete dynamics blocks, such as Integration, Transfer functions, Transport
Delay, etc.
Math blocks, such as Sum, Product, Add, etc.
Sources, such as Ramp, Random Generator, Step, etc.
Click the New icon on the Toolbar in order to create a new Simulink model:
The following window appears:
Create a new model
Wiring Technique:
Use the mouse to wire the inputs and outputs of the different blocks. Inputs are located on the
left side of the blocks, while outputs are located on the right side of the blocks.
Another wiring technique is to select the source block, then hold down the Ctrl key while left-
clicking on the destination block.
If wire a connection from a wire to another block, like the example below, you need to hold
down the Ctrl key while left-clicking on the wire and then to the input of the desired block.
Construct a simple circuit using Simulink by taking DC source and resistor from
Simulink library and connect their terminals
Example
Calculate the value of voltage and current of R load and also observe the output waveform using
dc source.
Example
Calculate the value of voltage and current of R load and display the result on Scope
To plot simple waveforms by using Matlab & Simulink.
Period
The period of a sinusoidal function is the amount of time, in seconds, that the sinusoid takes
to make a complete wave. The period of a sinusoid is always denoted with a capital T. This is
not to be confused with a lower-case t, which is used as the independent variable for time.
Frequency
Frequency is the reciprocal of the period, and is the number of times, per second, that the
sinusoid completes an entire cycle. Frequency is measured in Hertz (Hz). The relationship
between frequency and the Period is as follows:
f=1/T
Where f is the variable most commonly used to express the frequency.
Radian Frequency
Radian frequency is the value of the frequency expressed in terms of Radians Per Second,
instead of Hertz. Radian Frequency is denoted with the variable .The relationship between the
Frequency, and the Radian Frequency is as follows:
ω=2 πf
Phase
The phase is a quantity, expressed in radians, of the time shift of a sinusoid. A sinusoid
phase-shifted is moved forward by 1 whole period, and looks exactly the same.
An important fact to remember is this:
π −π
sin( −t)= cos(t) or sin(t)= cos(t )
2 2
Types of Periodic Waveforms:
Procedure
Task 1: To Generate Sine Wave At 50 Hz
Source Code:% Write source code on a separate .M File on Matlab
clear all;
close all;
clc;
f=50; %Defining a variable ‘frequency’
t=0:0.000005:0.02; %Continuous time from 0 to 0.02 with steps 0. 000005
x=sin(2*pi*f*t); % pi is built in function of MATLACB
plot(t,x)
Result:
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 0.002 0.004 0.006 0.008 0.01 0.012 0.014 0.016 0.018 0.02
Task 2: To Generate two Sine Waves one at 50 Hz and other at 100 Hz
Source Code:
clear all;
close all;
clc;
t=0:0.000005:0.02; % t is the time varying from 0 to 0.02
f1=50;
f2=100; % Plotting sinusoidal voltage of frequency 100Hz & 50Hz
v1=sin(2*pi*f1*t);
v2=sin(2*pi*f2*t);
plot(t,v1,t,v2) ;
xlabel('Voltage');
ylabel('Time in sec');
legend('50 Hz','100 Hz');
title('Voltage Waveforms');
Result:
Task 3: write source code of following sinusoids
v1(t)=5cos(2t+45 deg.)
v2(t)=2exp(-t/2)
v3(t)=10exp(-t/2) cos(2t+45 deg.)
Source Code:
clear all;
close all;
clc;
t=0:0.1:10;% t is the time varying from 0 to 10 in steps of 0.1s
v1=5*cos(2*t+0.7854);%degrees are converted in radians
plot(t,v1,'r')
grid ;
hold;
v2=2*exp(-t/2);
plot (t,v2,'g')
v3=10*exp(-t/2).*cos(2*t+0.7854);
plot (t,v3,'b')
title('Plot of v1(t), v2(t) and v3(t)')
xlabel ('Time in seconds')
ylabel ('Voltage in volts')
legend('v1(t)','v2(t)','v3(t)')
Result: