INTRODUCTION TO MATLAB
Presented by:
S P SIMON
DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING
NATIONAL INSTITUTE OF TECHNOLOGY
TIRUCHIRAPPALLI-620 015
CONTENTS
INTRODUCTION TO MATLAB ENVIRONMENT
DESKTOP TOOLS AND DEVELOPMENT ENVIRONMENT
MATHEMATICS
BASIC PROGRAMMING
GRAPHICS
INTRODUCTION TO SIMULINK
MATLAB TOOL BOXES
12/08/21 S.P.Simon-EEE-NITT 2
INTRODUCTION TO MATLAB ENVIRONMENT
INTRODUCTION TO MATLAB ENVIRONMENT
What is MATLAB?
A language for technical computing
An interactive system whose basic data element is a matrix
MATLAB stands for MATrix LABoratory
Typical Uses
Math and computation
Algorithm development
Modeling, simulation, and prototyping
Data analysis, exploration, and visualization
Scientific and engineering graphics
Application development including GUI
12/08/21 S.P.Simon-EEE-NITT 3
INTRODUCTION TO MATLAB ENVIRONMENT
THE MATLAB SYSTEM
Development Environment: This is the set of tools and facilities that help you use MATLAB
functions and files. Many of these tools are graphical user interfaces. It includes the MATLAB desktop and
Command Window, a command history, an editor and debugger, and browsers for viewing help, the
workspace, files, and the search path.
The MATLAB Mathematical Function Library : This is a vast collection of
computational algorithms ranging from elementary functions, like sum, sine, cosine, and complex
arithmetic, to more sophisticated functions like matrix inverse, matrix eigen values, Bessel functions, and
fast Fourier transforms.
The MATLAB Language: This is a high-level matrix/array language with control flow
statements, functions, data structures, input/output, and object-oriented programming features. It allows
both "programming in the small" to rapidly create quick and dirty throw-away programs, and
"programming in the large" to create large and complex application programs.
Graphics: MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as
annotating and printing these graphs. It includes high-level functions for two-dimensional and three-
dimensional data visualization, image processing, animation, and presentation graphics. It also includes
low-level functions that allow you to fully customize the appearance of graphics as well as to build
complete graphical user interfaces on your MATLAB applications.
The MATLAB Application Program Interface (API): This is a library that allows
you to write C and Fortran programs that interact with MATLAB. It includes facilities for calling routines
from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing
MAT-files.
12/08/21 S.P.Simon-EEE-NITT 4
INTRODUCTION TO MATLAB ENVIRONMENT
DESKTOP TOOLS AND DEVELOPMENT ENVIRONMENT
12/08/21 S.P.Simon-EEE-NITT 5
INTRODUCTION TO MATLAB ENVIRONMENT
Command
Variable
window
browser
Start Matlab from the
“start” menu
The command window is
the dynamic command
interpreter which allows
the user to issue Matlab
commands
The variable browser
shows which variables
currently exist in the
workspace
The command history
shows which commands
have been executed in the
past
12/08/21 S.P.Simon-EEE-NITT 6
Command history
INTRODUCTION TO MATLAB ENVIRONMENT
CREATING MATLAB SCRIPTS
Commands can be typed directly into the command
window (like a calculator), or they can be grouped
together into a script file (or function)
A script is a text file with a “.m” extension
(remember to change to your directory before
doing any work
cd p:/matlab)
A script file can be created using the Matlab editor
edit TestScript.m
Just type the commands into the file
The script can be run by typing the name of the
script in the command window (or press F5)
TestScript
Any variables created in the script will be visible in
the workspace which are viewed in the variable
browser
12/08/21 S.P.Simon-EEE-NITT 7
INTRODUCTION TO MATLAB ENVIRONMENT
WORKSPACE
save my.dat
clear
clc
who
load my.dat -mat
who
workspace = the area of memory used by the MATLAB
who = lists the current variables in the workspace
clear = clear the workspace
save = save the workspace variables to a file.
load = load all variables from a specified file.
12/08/21 S.P.Simon-EEE-NITT 8
MATHEMATICS
MATRICES IN MATLAB
MATRICES GENERATION
eye - Identity matrix
ones - Matrix with all
elements = 1
Contd..
12/08/21 S.P.Simon-EEE-NITT 9
MATHEMATICS
rand – Random matrix zeros - Matrix with all
elements = 0
Given:
Matrix Index
Always starts with 1 (not 0)
12/08/21 S.P.Simon-EEE-NITT 10
MATHEMATICS
MATRICES OPERATIONS
Given A and B:
Addition Subtraction Product Transpose
12/08/21 S.P.Simon-EEE-NITT 11
MATHEMATICS
THE USE OF “.” – “ELEMENT” OPERATION
Given A:
Divide each element Multiply each element Square each element
of A by 2 of A by 3 of A
12/08/21 S.P.Simon-EEE-NITT 12
MATHEMATICS
USEFUL FUNCTIONS
Function Description
rank Matrix rank
det Determinant
null Null space
\ and / Linear equation solution
inv Matrix inverse
eig Eigenvalues and eigenvectors
poly Characteristic polynomial
12/08/21 S.P.Simon-EEE-NITT 13
MATHEMATICS
EXAMPLES
Given B:
Inverse of B Determinant of B Eigenvalues of B
12/08/21 S.P.Simon-EEE-NITT 14
MATHEMATICS
GET HELP FOR USE OF FUNCTIONS
>>help function_name
>>lookfor keyword
12/08/21 S.P.Simon-EEE-NITT 15
MATHEMATICS
SOLVING LINEAR EQUATIONS
Given A and B:
Solve for X, s.t. AX = B Check that AX = B
Note: X = A\B denotes AX = B,
X = B/A denotes XA = B
12/08/21 S.P.Simon-EEE-NITT 16
MATHEMATICS
USE OF M FILE
Click to create
a new M-File
Extension “.m”
A text file containing script or function or program to run
You can run more than 1 line of commands at a time
12/08/21 S.P.Simon-EEE-NITT 17
MATHEMATICS
M-FILE AS SCRIPT FILE
Save file as filename.m
Type what you want
to do, eg. Create
matrices
If you include “;” at the
end of each statement,
result will not be shown
immediately
12/08/21 S.P.Simon-EEE-NITT 18
MATHEMATICS
RUN THE M-FILE
Run the file by typing the filename in the command window
That’s because the file path is not defined
12/08/21 S.P.Simon-EEE-NITT 19
MATHEMATICS
TO
RUNADD
THEPATH
M-FILE File – Set Path…
Add Folder…
Select the folder where
you placed your M-File
12/08/21 S.P.Simon-EEE-NITT 20
MATHEMATICS
RUN AGAIN
Type the M-File name again
Notice that the statement that
does not have “;” at the end will
have the result shown immediately
12/08/21 S.P.Simon-EEE-NITT 21
MATHEMATICS
RUN AGAIN 2
If you want to see the values of
the statement that has “;” at the end,
simply type the valuable name and
press Enter
12/08/21 S.P.Simon-EEE-NITT 22
BASIC PROGRAMMING
COMMANDS PARSED & EXECUTED IN ORDER
%% Comments
Comments start
start with
with "%"
"%" character
character
pause
pause %% Suspend
Suspend execution
execution -- hit
hit any
any key
key to
to continue.
continue.
keyboard
keyboard %% Pause
Pause && return
return control
control to
to command
command line.
line.
%% Type "return" to continue.
Type "return" to continue.
break
break %% Terminate
Terminate execution
execution of
of current
current loop/file.
loop/file.
return
return %% Exit
Exit current
current function
function
%% Return
Return to invoking function/command
to invoking function/command line.
line.
FLOW CONTROL CONSTRUCTS
Logic Control:
IF / ELSEIF / ELSE
SWITCH / CASE / OTHERWISE
Iterative Loops:
FOR
WHILE
12/08/21 S.P.Simon-EEE-NITT 23
BASIC PROGRAMMING
THE IF, ELSEIF AND ELSE STATEMENTS
Works on Conditional
statements
Short-circuited in MATLAB -
once a condition is true, the
sequence terminates.
»if_examp
i, j = imaginary unit
※ Don't use i or j as a variable except for-loop index!!!
12/08/21 S.P.Simon-EEE-NITT 24
BASIC PROGRAMMING
SWITCH, CASE, AND OTHERWISE
More efficient than switch
switchinput_num
input_num
elseif statements case
case-1-1
Only the first matching input_str
input_str=='minus
'minusone';
one';
case is executed case
case00
input_str
input_str=='zero';
'zero';
case
case11
input_str
input_str=='plus
'plusone';
Relational operators case
case{-10,10}
{-10,10}
one';
< <= > >= == ~= input_str
input_str=='+/-
'+/-ten';
ten';
true = 1 false = 0 otherwise
otherwise
input_str
input_str=='other
'othervalue';
value';
Logical operators end
end
& | ~
12/08/21 S.P.Simon-EEE-NITT 25
BASIC PROGRAMMING
THE FOR LOOP
Similar to other
programming languages
Repeats loop a set
number of times (based N=10;
on index) N=10;
for
for II =
= 1:N
1:N
Can be nested for
for JJ =
= 1:N
1:N
A(I,J)
A(I,J) = = 1/(I+J-1);
1/(I+J-1);
end
end
end
end
12/08/21 S.P.Simon-EEE-NITT 26
BASIC PROGRAMMING
THE WHILE LOOP
Similar to other
programming languages
I=1;
I=1; N=10;
N=10;
Repeats loop a set
number of times (based while
while I<=N
I<=N
on index) J=1;
J=1;
Can be nested while
while J<=N
J<=N
A(I,J)=1/(I+J-
A(I,J)=1/(I+J-
1);
1);
J=J+1;
J=J+1;
end
end
I=I+1;
I=I+1;
end
end
12/08/21 S.P.Simon-EEE-NITT 27
BASIC PROGRAMMING
ARRAY OPERATION
Using Array Operations:
Density
Density =
= Mass(I,J)/(Length.*Width.*Height);
Mass(I,J)/(Length.*Width.*Height);
Using Loops:
[rows,
[rows, cols]
cols] =
= size(M);
size(M);
for
for II =
= 1:rows
1:rows
for
for JJ =
= 1:cols
1:cols
Density(I,J)
Density(I,J) = = M(I,J)/(L(I,J)*W(I,J)*H(I,J));
M(I,J)/(L(I,J)*W(I,J)*H(I,J));
end
end
end
end
»array_vs_loops
12/08/21 S.P.Simon-EEE-NITT 28
BASIC PROGRAMMING
M-FILE FUNCTIONS
Function name
has the same constraints as variable name
ONE function in ONE file cf) subfunction
file name > function name
The name of the M-file and of the function SHOULD be the same
Function name resolution
Check to see if the name is a variable
Check to see if the name is a subfunction
Check to see if the name is a function on the current directory
Check to see if the name is a function on the MATLAB search path
12/08/21 S.P.Simon-EEE-NITT 29
BASIC PROGRAMMING
STRUCTURE OF A FUNCTION M-FILE
Keyword: function Function Name (same as file name .m)
Output Argument(s) Input Argument(s)
function
function yy =
= mean(x)
mean(x)
%
%MEAN
MEANAverage
Averageorormean
meanvalue.
value.
%
%For
Forvectors,
vectors,MEAN(x)
MEAN(x)returns
returnsthe
themean
meanvalue.
value.
Online %
%For
Formatrices,
matrices,MEAN(x)
MEAN(x)isisaarow
rowvector
vector
Help %
%containing
containingthe
themean
meanvalue
valueof ofeach
eachcolumn.
column.
[m,n]
[m,n] =
= size(x);
size(x);
ifif m
m ==
== 11
MATLAB
Code mm== n;
n;
end
end
12/08/21
yy =
= sum(x)/m;
sum(x)/m;
S.P.Simon-EEE-NITT 30
»output_value = mean(input_value) Command Line Syntax
BASIC PROGRAMMING
M-FILE FUNCTIONS
local and global variables
function value=tg(x, y)
global Z
x1 = x^2; y1 = y^2; Z1 = Z^2
value=x1+y1+z1; return
save as tg.m
Declare the variable as global in every function that requires access to it
Issue the global command at the top of the M-file (Recommended!!)
global Z
x = 3; y = 4; Z= 5;
tg(x, y)
x, y, Z
save as test.m and run test!
12/08/21 S.P.Simon-EEE-NITT 31
BASIC PROGRAMMING
M-FILE FUNCTIONS
eval and feval
for n = 1:12
eval(['M' num2str(n) ' = magic(n)'])
end
eval : execute the contents of bracket in command window
for n = 0:pi/10:pi
m=feval('sin',n);
disp([n m])
end
feval : evaluate function by function name and argument(s) in bracket
12/08/21 S.P.Simon-EEE-NITT 32
GRAPHICS
BASIC 2-D GRAPHICS
Creating a Plot
t = 0:pi/100:2*pi;
y = sin(t);
plot(t, y)
plot(x, y) = produces a 2D graph of y vs. x
figure
y2 = sin(t - 0.25);
plot(t, y2)
hold on
plot(t, y+y2)
figure = open a new figure window
hold on/off = allows you to add plots to an existing graph ans = the
variable which stores the results of most recent answer
12/08/21 S.P.Simon-EEE-NITT 33
GRAPHICS
BASIC 2-D GRAPHICS
plot Command
y3 = sin(t - 0.5);
plot(t, y, t, y2, t, y3)
plot(x1, y1, x2, y2, ...)
plot(t, y, 'c--', t, y2, 'r.')
plot(x1, y1, 'color_style_marker', x2, y2, 'color_style_marker, ...)
color_style_marker = a 1/2/3 character string.
color = c, m, y, r, g, b, w, k
style = -, --, :, -., none
marker = +, o, *, x
12/08/21 S.P.Simon-EEE-NITT 34
GRAPHICS
BASIC 2-D GRAPHICS
Subplots
clf
y4 = cos(t);
subplot(2, 2, 1); plot(t, y)
subplot(2, 2, 2); plot(t, y2)
subplot(2, 2, 3); plot(t, y3)
subplot(2, 2, 4); plot(t, y4)
clf = clear the current figure window
subplot = display multiple plots in the same window
12/08/21 S.P.Simon-EEE-NITT 35
GRAPHICS
BASIC 2-D GRAPHICS
Axes
clf
t = -pi:pi/100:pi;
y = sin(t);
plot(t, y)
grid on
axis([-pi pi -1 1])
xlabel('\pi \leq \itt \leq \pi')
ylabel('sin(t)')
grid on = draw the grid lines
axis([xmin xmax ymin ymax]) = set scaling for the axes
xlabel/ylabel = adds text beside the X-axis/Y-axis
12/08/21 S.P.Simon-EEE-NITT 36
GRAPHICS
BASIC 3-D GRAPHICS
plot3(x,y,z)
plots x,y,z in 3-dimentional space
t=(0:pi/10:8*pi);
x=exp(-t/20).*cos(t);
y=exp(-t/20).*sin(t);
z=t;
figure(1); plot3(x,y,z);
xlabel('x'); ylabel('y'); zlabel('z');
view(Az,El)
Specifies the viewing point in 3-dimentional plot
view(20,70); view(2); view(3);
12/08/21 S.P.Simon-EEE-NITT 37
GRAPHICS
BASIC 3-D GRAPHICS
meshgrid(x,y)
generates domain for plotting
x=(-5:0.2:5);
y=(-5:0.2:5);
[X,Y] = meshgrid(x,y);
Z= X .* exp(-X.^2 - Y.^2);
size(X); size(Y); size(Z);
mesh(Z)
plots colored meshed 3-D graph
mesh(Z); mesh(X,Y,Z);
12/08/21 S.P.Simon-EEE-NITT 38
GRAPHICS
BASIC 3-D GRAPHICS
surf
plots 3-d surface graphs
surf(X,Y,Z)
contour
plots 3-d surface graphs
[cs,h]=contour(Z)
clabel(cs,h);
colorbar;
12/08/21 S.P.Simon-EEE-NITT 39
SIMULINK
INTRODUCTION TO SIMULINK
Simulink is a graphical, “drag and drop” environment for building
continuous time signal and system simulations.
It allows users to concentrate on the structure of the problem, rather than
having to worry (too much) about a programming language.
The parameters of each signal and system block is configured by the user
(right click on block)
Signals and systems are simulated over a particular time.
12/08/21 S.P.Simon-EEE-NITT 40
SIMULINK
STARTING SIMULINK
Type the following at the Matlab command prompt
simulink
The Simulink library will appear
Note that you can also start Simulink by clicking
on the icon on the Matlab toolbar
Select
File – New Model
To create a new area (model) to build signals
and systems
12/08/21 S.P.Simon-EEE-NITT 41
SIMULINK
SIGNALS IN SIMULINK
There are two main libraries for manipulating
signals in Simulink:
Sources: generate a signal
Sinks: display, read or store a signal
12/08/21 S.P.Simon-EEE-NITT 42
SIMULINK
CREATE AND VIEW A CONTINUOUS TIME SIGNAL
Drag Sine Wave source and Scope sink onto
the new Simulink Model and connect them
(click on Sine Wave block, hold down Ctrl and
click on the Scope)
Modify Sine Wave parameters to 2 rad/sec,
by right clicking on Sine Wave block and
selecting Sin Parameters, and modify
frequency
Run the simulation
Simulation - Start
Open the scope and leave open while you
change parameters (Sine Wave or Simulation
Parameters) and re-run
You can save the simulation using File -
Save
12/08/21 S.P.Simon-EEE-NITT 43
TOOLBOXES
MATLAB TOOLBOXES/BLOCK SETS
Simulink Version 6.1 (R14SP1)
Aerospace Blockset Version 1.6.1 (R14SP1)
Bioinformatics Toolbox Version 1.1.1 (R14SP1)
CDMA Reference Blockset Version 1.1 (R14SP1)
Communications Blockset Version 3.0.1 (R14SP1)
Communications Toolbox Version 3.0.1 (R14SP1)
Control System Toolbox Version 6.1 (R14SP1)
Curve Fitting Toolbox Version 1.1.2 (R14SP1)
Data Acquisition Toolbox Version 2.5.1 (R14SP1)
Database Toolbox Version 3.0.1 (R14SP1)
Datafeed Toolbox Version 1.6 (R14SP1)
Embedded Target for Infineon C166 Microcontrollers Version 1.1.1 (R14SP1)
Embedded Target for Motorola HC12 Version 1.1.1 (R14SP1)
Embedded Target for Motorola MPC555 Version 2.0.1 (R14SP1)
Embedded Target for OSEK VDX Version 1.1.1 (R14SP1)
Embedded Target for TI C2000 DSP(tm) Version 1.1.1 (R14SP1)
Embedded Target for TI C6000 DSP(tm) Version 2.2.1 (R14SP1)
Excel Link Version 2.2.1 (R14SP1)
Extended Symbolic Math Version 3.1.1 (R14SP1)
Filter Design HDL Coder Version 1.1 (R14SP1)
Filter Design Toolbox Version 3.1 (R14SP1)
Financial Derivatives Toolbox Version 3.0.1 (R14SP1)
12/08/21 S.P.Simon-EEE-NITT 44
TOOLBOXES
MATLAB TOOLBOXES/BLOCK SETS
Financial Time Series Toolbox Version 2.1.1 (R14SP1)
Financial Toolbox Version 2.4.2 (R14SP1)
Fixed-Income Toolbox Version 1.1 (R14SP1)
Fixed-Point Toolbox Version 1.1 (R14SP1)
Fuzzy Logic Toolbox Version 2.2 (R14SP1)
GARCH Toolbox Version 2.0.1 (R14SP1)
Gauges Blockset Version 2.0 (R14SP1)
Genetic Algorithm Direct Search Toolbox Version 1.0.2 (R14SP1)
Image Acquisition Toolbox Version 1.7 (R14SP1)
Image Processing Toolbox Version 5.0.1 (R14SP1)
Instrument Control Toolbox Version 2.1 (R14SP1)
Link for Code Composer Studio Version 1.3.2 (R14SP1)
Link for ModelSim Version 1.2 (R14SP1)
MATLAB Builder for COM Version 1.1.2 (R14SP1)
MATLAB Builder for Excel Version 1.2.2 (R14SP1)
MATLAB Compiler Version 4.1 (R14SP1)
MATLAB Report Generator Version 2.1.1 (R14SP1)
MATLAB Web Server Version 1.2.3 (R14SP1)
Mapping Toolbox Version 2.0.3 (R14SP1)
Model Predictive Control Toolbox Version 2.1 (R14SP1)
Model-Based Calibration Toolbox Version 2.1.2 (R14SP1)
Neural Network Toolbox Version 4.0.4 (R14SP1)
OPC Toolbox Version 1.1.1 (R14SP1)
Optimization Toolbox Version 3.0.1 (R14SP1)
Partial Differential Equation Toolbox Version 1.0.6 (R14SP1)
12/08/21 S.P.Simon-EEE-NITT 45
TOOLBOXES
MATLAB TOOLBOXES/BLOCK SETS
RF Blockset Version 1.0.2 (R14SP1)
RF Toolbox Version 1.0.1 (R14SP1)
Real-Time Windows Target Version 2.5.1 (R14SP1)
Real-Time Workshop Version 6.1 (R14SP1)
Real-Time Workshop Embedded Coder Version 4.1 (R14SP1)
Robust Control Toolbox Version 3.0 (R14SP1)
Signal Processing Blockset Version 6.0.1 (R14SP1)
Signal Processing Toolbox Version 6.2.1 (R14SP1)
SimMechanics Version 2.2.1 (R14SP1)
SimPowerSystems Version 4.0 (R14SP1)
Simulink Accelerator Version 6.0.1 (R14SP1)
Simulink Control Design Version 1.1 (R14SP1)
Simulink Fixed Point Version 5.0.1 (R14SP1)
Simulink Parameter Estimation Version 1.1 (R14SP1)
Simulink Report Generator Version 2.1.1 (R14SP1)
Simulink Verification and Validation Version 1.0.1 (R14SP1)
Spline Toolbox Version 3.2.1 (R14SP1)
Stateflow Version 6.1 (R14SP1)
Stateflow Coder Version 6.1 (R14SP1)
Statistics Toolbox Version 5.0.1 (R14SP1)
Symbolic Math Toolbox Version 3.1.1 (R14SP1)
System Identification Toolbox Version 6.1 (R14SP1)
Virtual Reality Toolbox Version 4.0.1 (R14SP1)
Wavelet Toolbox Version 3.0.1 (R14SP1)
xPC Target Version 2.6.1 (R14SP1)
xPC Target Embedded Option Version 2.6.1 (R14SP1)
12/08/21 S.P.Simon-EEE-NITT 46
12/08/21 S.P.Simon-EEE-NITT 47