Workshop on
MATLAB
By
Mr. Rahul Kumar Gupta
M.Tech. (ECE-VLSI), IIT Dhanbad
B.Tech. (ECE), DTU, Delhi
Assistant Professor - EEE , Lingaya's Vidyapeeth, Faridabad, Haryana
Contact No.:+91-8802286651
What is MATLAB?
Stands for Matrix Laboratory.
A special-purpose computer program optimized to perform
engineering and scientific calculations.
An interactive system whose basic data element is an array
that does not require dimensioning.
This allows the capabilities to solve many technical computing
problems. Especially those with matrix and vector
formulations.
Utilizes many functions and toolboxes to help in various
applications
• It is a high-performance language for technical
computing.
• It integrates computation, visualization, and
programming in an easy-to-use environment
• Typical uses include:
– Math and computation
– Algorithm development
– Modelling, simulation and prototyping
– Data analysis, exploration and visualization
– Scientific and engineering graphics
– Application development, including Graphical User
Interface (GUI) building
MATLAB Features
• family of application-specific solution called
Toolboxes.
• Toolboxes are comprehensive collections of MATLAB
function (m-files) that extend the MATLAB
environment to solve particular classes of problems.
• Areas in which toolboxes are available:
– signal processing
– control systems
– neural networks
– fuzzy logic
– Wavelets
– image processing
Math and Analysis Signal & Image Processing
Optimization Signal Processing
Requirements Management Interface Image Processing
Statistics Communications
Neural Network Frequency Domain System Identification
Symbolic/Extended Math Higher-Order Spectral Analysis
Partial Differential Equations System Identification
PLS Toolbox Wavelet
Mapping Filter Design
Spline
Control Design
Data Acquisition and Import Control System
Data Acquisition Fuzzy Logic
Instrument Control Robust Control
Excel Link μ-Analysis and Synthesis
Portable Graph Object Model Predictive Control
Intro MATLAB
The Advantages of MATLAB
• Ease of Use. MATLAB is an interpreted language.
Program may be easily written and modified with
the built-in integrated development environment
and debugged with the MATLAB debugger.
• Platform Independence. MATLAB is supported on
many different computer systems, providing a
large measure of platform independence.
• Predefined Function. MATLAB comes complete
with an extensive library of predefined functions
that provide tested and pre-packaged solutions to
many basic technical tasks.
• Device-Independent Plotting. The plots and
images can be displayed on any graphical output
device
• Graphical User Interface. MATLAB includes tools
that allow a programmer to interactively construct
a graphical user interface, (GUI).
Disadvantages of MATLAB
• Slow: It is an interpreted language and therefore can
execute more slowly than compiled languages.
• Cost: a full copy of MATLAB is five to ten times more
expensive than a conventional C or Fortran compiler
or Python
What is Matlab?
• Matlab is basically a high level language which
has many specialized toolboxes for making
things easier for us
• How high?
Matlab
High Level
Languages such as
C, Pascal etc.
Assembly
Application of MATLAB
Math and computation
Algorithm development
Modeling, simulation, and prototyping
Data analysis, exploration, and visualization
Scientific and engineering graphics
Application development, including graphical user
interface building
MATLAB Worldwide
Aerospace and Defense
Automotive
Biotech, Medical, and
Pharmaceutical
Chemical and Petroleum
Communications
Computers and Office
Equipment
Education
Electronics and
Semiconductor
Financial Services
Industrial Equipment and
Machinery
Instrumentation
Utilities and Energy
Starting MATLAB
• MATLAB display several types of windows that
accept commands or display information.
• The major tools within or accessible from the
MATLAB desktop are:
– The Current Directory Browser
– The Workspace Window
– The Command Window
– The Command History Window
– The Start Button
– The Help Window
MATLAB Layout
Editor Window
• write and save program Current Folder
• View folders
and m-files
Command History
Workspace • view past commands
• View program variables • save a whole session
Command Window
• Type commands/program • Double click on a variable using diary
• Display output(s) to see it in the Variable Editor
MATLAB Variable names
– Variable names are case sensitive.
– Variable names can contain up to 63 characters
– Variable names must start with a letter and can be
followed by letters, digits and underscores.
Variables and Arrays
• 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
1 2 3
A 4 5 6 A B ?
7 8 9
4 3
B
A* B ?
1 2
1 2 3
A 4 5 6 A3 X 3 B2 X 2
Error using +
Matrix dimensions must agree.
7 8 9 3 X 3
4 3
B A3 X 3 * B2 X 2 Error using *
Inner matrix dimensions must
1 2 2X 2 agree.
1 2 3 1 2 3
A 4 5 6 A B ? A .* B ? 4 5 6
7 8 9 7 8 9
1 1 1
B 1 1 1 A* B ?
1 1 1
1 2 3 2 3 4
A 4 5 6 A B
5 6 7
7 8 9 3 X 3 8 9 10
1 1 1 6 6 6
B 1 1 1 A* B 15 15 15
1 1 1 3 X 3 24 24 24
1 2 3
A 4 5 6
7 8 9
Long Array, Matrix
Generating Vectors from functions
• zeros(M,N) MxN matrix of zeros x = zeros(1,3)
x =
0 0 0
• ones(M,N) MxN matrix of ones
x = ones(1,3)
x =
1 1 1
• rand(M,N) MxN matrix of uniformly
distributed random x = rand(1,3)
numbers on (0,1) x =
0.9501 0.2311
0.6068
Functions
MATLAB provides a large number of functions that perform computational tasks.
help Help for functions in Command Window
clc Clear Command Window
clear Remove items from workspace, freeing up system memory
length Length of vector or largest array dimension
max Largest elements in array
min Smallest elements in array
size Array dimensions
eye Identity matrix
sum Returns the sum of the elements in a matrix
sort Returns the sorted elements in a matrix
abs Returns the absolute value of the elements in a matrix
MATLAB
Plotting and Visualization
Creating a Plot
• MATLAB has extensive facilities for displaying vectors
and matrices as graphs, as well as annotating and
printing these graphs.
• The plot function has different forms, depending on
the input arguments.
• If y is a vector, plot(y) produces a piecewise linear
graph of the elements of y versus the index of the
elements of y.
• If you specify two vectors as arguments, plot(x,y)
produces a graph of y versus x.
Creating Line Plots
to plot the value of the sine function from zero to 2π:
>> x = 0:pi/100:2*pi;
>> y = sin(x);
>> plot(x,y);
Titles and Labels
• MATLAB has commands which will let you add titles and
labels and others in order to make your figures more
readable.
>> xlabel(‘Radian’);
>> ylabel(‘Amplitude’);
>> title(‘Plot of sin(x) vs x’);
>> grid on;
• The current limits of this plot can be determined from
the basic axis function. So, in order to modify the x-axis
within [0 2π], you need to run this function:
>> axis([0 2*pi -1 1]);
Specifying the Color and Size of Lines
LineWidth Width of the line in units of points
MarkerEdgeColor Color of the marker or the edge color for filled
markers
MarkerFaceColor Color of the face of filled markers
MarkerSize Size of the marker in units of points
Example
>> x = -pi:pi/10:pi;
>> y = tan(sin(x)) - sin(tan(x));
>> plot(x,y,'--rs','LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g','MarkerSize',10);
Multiple Plots : The subplot Function
>> x = linspace(0,2*pi);
>> subplot(2,2,1);
>> plot(x,sin(x));
>>
>> subplot(2,2,2)
>> plot(x,sin(2*x));
>>
>> subplot(2,2,3)
>> plot(x,sin(3*x));
>>
>> subplot(2,2,4)
>> plot(x,sin(4*x));
Multiple plots
>> x = linspace(0,2*pi);
>> y1 = sin(x);
>> y1 = cos(x);
>> y1 = tan(x);
>> plot(x,y1,x);
>> axis([0 2*pi -1 1]);
The hold Function
• command will add new plots on top of previously
existing plots.
>> x = -pi:pi/20:pi;
>> y1 = sin(x);
>> y2 = cos(x);
>> plot(x,y1,'b-');
>> hold on;
>> plot(x,y2,'g--');
>> hold off;
>>
legend('sin(x)','cos(x)');
Three-Dimensional Surface Mesh Plots
• The first step in displaying a function of two variables, z = f(x,y), is to generate X
and Y matrices consisting of repeated rows and columns,
• Then use these matrices to evaluate and graph the function.
• Meshgrid function transforms the domain specified by two-vectors, x and y, into
matrices X and Y.
>> [X,Y] = meshgrid(-8:.5:8);
>> R = sqrt(X.^2 + Y.^2);
>> Z = sin(R)./R;
>> mesh(X,Y,Z);
Line Plots in Three-Dimensions
• The three-dimension analog of the plot function is plot3. if x, y and z are three
vectors of the same length, plot3(x,y,z) generates a line in 3-D through the points
whose coordinates are the elements of x, y and z and then produces a 2-D
projection of that line on the screen
>> Z = [0 : pi/50 : 10*pi];
>> X = exp(-.2.*Z).*cos(Z);
>> Y = exp(-.2.*Z).*sin(Z);
>>
plot3(X,Y,Z,'LineWidth',2);
>> grid on;
>> xlabel('x-axis');
>> ylabel('y-axis');
>> zlabel('z-axis');
Subplots
• The subplot function allows to display multiple plots in
the same window. Typing subplot(m,n,p) breaks the
figure window into an m-by-n matrix of small subplots
and selects the pth subplot for the current plot.
e.g
t = 0:pi/10:2*pi;
[x,y,z] = cylinder(4*cos(t));
subplot(2,2,1)
mesh(x)
subplot(2,2,2); mesh(y)
subplot(2,2,3); mesh(z)
subplot(2,2,4); mesh(x,y,z)
Controlling Axes
axis([xmin xmax ymin ymax])
axis square %makes the entire x-axes and y-axes the same length
axis equal % makes the individual tick mark increments on the x-
and y-axes the same length.
axis auto % returns the axis scaling to its default, automatic mode
axis on % turns on axis labeling and tick marks
axis off %turns off axis labeling and tick marks.
grid off %turns the grid lines off and grid on % turns them back
on again.
xlabel, ylabel,and zlabel % add x, y, and z axis labels
title % adds a title at the top of the figure
text % inserts text anywhere in the figure
e.g. t= –pi:pi/100:pi;
y = sin(t);
plot(t, y)
axis([–pi pi –1 1])
xlabel('–\pi \leq {\itt} \leq \pi')
ylabel('sin(t)')
title('Graph of the sine function')
text(1,–1/3,'\it{Note the odd symmetry.}')
Flow Control
• if
• switch
• for
• while
• break
Operators (relational, logical)
Control Structures
Some Dummy Examples
• If Statement Syntax
if ((a>3) & (b==5))
Some Matlab Commands;
if (Condition_1) end
Matlab Commands
if (a<3)
elseif (Condition_2) Some Matlab Commands;
Matlab Commands elseif (b~=5)
Some Matlab Commands;
elseif (Condition_3) end
Matlab Commands
if (a<3)
else Some Matlab Commands;
Matlab Commands else
end Some Matlab Commands;
end
• e.g.Given the following bus fare schedule:
• Regular fare Rs 10
• Children under 5 free
• Youth fare (ages 5-17)Rs. 5
• Senior fare (age 65+) Rs.5
– Goal: write a piece of code that determines a
passenger's fare
Matlab Script
%suppose age contains the passenger's age
fare = 10;
if age < 5
fare = 0;
disp('Under 5, free')
end
if (age >= 5 & age <= 17) || age >= 65
fare = 5;
disp('Discount fare')
end
‘switch’ statement
• switch Switch among several Example :
cases based on expression
x = 2;
The general form of the switch y = 3;
statement is: switch x
switch switch_expr case x==y
case case_expr1 disp('x and y are equal');
…
case case_expr2
case x>y
… disp('x is greater than y');
otherwise otherwise
…
end disp('x is less than y');
end
‘for’ loop
• for Repeat statements a Some Dummy Examples
specific number of times
for i=1:100
Some Matlab Commands;
The general form of a for end
statement is for j=1:3:200
Some Matlab Commands;
end
for variable=expression
for m=13:-0.2:-21
…
Some Matlab Commands;
… end
end for k=[0.1 0.3 -13 12 7 -9.3]
Some Matlab Commands;
end
Examples
Example 1:
for x = 0:0.05:1
printf(‘%d\n’,x);
end
Example 2: Sum of squares of odd numbers from 1 to 20
SumSq = 0;
for n = 1 : 2: 20
SumSq = SumSq + n^2;
end
SumSq
‘while’ loop
• while Repeat statements an
indefinite number of times
Dummy Example
while (condition)
Matlab Commands while ((a>3) & (b==5))
Some Matlab Commands;
end end
Examples
Example 1:
x = 1;
while x
disp(‘Infinite Loop: Please
press ctrl+C’)
end
Example 2: Sum of squares of even numbers from 1 to 20
SumSq = 0;
n = 2;
while n <= 20
SumSq = SumSq + n^2;
n = n+2
end
SumSq
Examples
e.g. Fibonacci numbers are 1, 1, 2, 3, 5, 8, …
• Goal: write a piece of Matlab code to find the first N=10
Fibonacci numbers.
N = 10;
fib = [1 1];
for k = 3 : N
fib(k) = fib(k-1) + fib(k-2);
end
disp(['The first ', num2str(N), ' Fibonacci numbers
are: '])
disp(fib)
‘break’ statement
• break terminates the execution of for and while loops
• In nested loops, break terminates from the innermost loop only
Example:
y = 3;
for x = 1:10
printf(‘%5d’,x);
if (x>y)
break;
end
end
1234
Efficient Programming in MATLAB
Avoid using nested loops as far as possible
In most cases, one can replace nested loops with efficient
matrix manipulation.
Pre-allocate your arrays when possible
MATLAB comes with a huge library of in-built functions, use
them when necessary
Avoid using your own functions, MATLAB’s functions are more
likely to be efficient than yours.
More examples
• Find the number of positive numbers in a vector
x = input( 'Enter a vector: ' );
count = 0;
for ii = 1:length(x),
if ( x(ii) > 0 ),
count = count + 1;
end
end
fprintf('Number of positive numbers is %d\n',
count);
• Find the index of the largest number in a vector
x = input( 'Enter a vector: ' );
max_value = x(1);
max_index = 1;
for ii = 2:length(x),
if ( x(ii) > max_value ),
max_value = x(ii);
max_index = ii;
end
end
fprintf( 'Max value is %d\n', max_value );
fprintf( 'Its index is %d\n', max_index );
Character Strings
• What if you want to define an array that has numbers and
string?. Like an address book that has name, address,
phone number. This is possible using structure .A structure
is like an array except that it can contain dissimilar &
unrelated objects. concatenation with blank or with “,”
• >> s.name=‘Shivam’;
• >> s.adds=‘ 29 Cranes Software’;semi-colon: join vertically
• >> s.tel=9213975800
MATLAB
Programming
M-File Programming
• A full programming language that
– enables you to write a series of MATLAB statements into a
file
– execute them with a single command.
• Write a program in an ordinary text file, giving the file a name
of filename.m
• The term use for filename becomes the new command that
MATLAB associates with the program.
• The file extension of .m makes this a MATLAB M-file.
• M-files can be scripts that simply execute a series of MATLAB
statements, or they can be functions that also accept
arguments and produce output.
Scripts and Functions
• There are two kinds of M-files:
- Scripts, which do not accept input arguments or return
output arguments. They operate on data in the
workspace. Any variables that they create remain in the
workspace, to be used in subsequent computations
- Functions, which can accept input arguments and
return output arguments. Internal variables are local to
the function.
Scripts
• Scripts are the simplest kind of M-file because they
have no input or output arguments.
• They're useful for automating series of MATLAB
commands, such as computations that you have to
perform repeatedly from the command line.
• Scripts operate on existing data in the workspace, or
they can create new data on which to operate.
• Any variables that scripts create remain in the
workspace after the script finishes so you can use
them for further computations.
Matlab Editor
MATLAB Script Files
% This is a MATLAB script file.
% It has been saved as “g13.m".
load g13.dat; %Load data file
voltage = g13( : , 4); %Extract volts vector
time = .005*[1:length(voltage)]; %Create time vector
plot (time, voltage) %Plot volts vs time
xlabel ('Time in Seconds') % Label x axis
ylabel ('Voltage') % Label y axis
title ('Bike Strain Gage Voltage vs Time')
grid %Put a grid on graph
Writing User Defined Functions
A MATLAB function file (called an M-file) is a text file that
contains a MATLAB function and, optionally, comments.
The file is saved with the function name and the usual
MATLAB script file extension, ".m".
A MATLAB function may be called from the command line or
from any other M-file.
Since the function is not part of the MATLAB workspace, its
variables and their values are not known after control is
returned.
Writing User Defined Functions
The syntax for a MATLAB function definition is:
function [val1, … , valn] = myfunc (arg1, … , argk)
where val1 through valn are the specified returned values
from the function and arg1 through argk are the values
sent to the function.
• Functions are M-files that accept input arguments and
return output arguments.
• They operate on variables within their own workspace.
• This is separate from the workspace you access at the
MATLAB command prompt
The Function Definition Line
• Informs MATLAB that the M-file contains a function,
and specifies the argument calling sequence of the
function.
Loading Data
• Suppose that we want to load a Use MATLAB function load to
data stored in a text file like one load the data onto MATLAB
workspace and save it as
shown below. The name of the variable A
file is ‘simpledata.txt’. A = load('simpledata.txt');
.
Now, if we type A in MATLAB,
we’ll get:
>> A
A=
1
2
3
4
5
4
3
2
1
More examples
• Find the number of positive numbers in a vector
x = input( 'Enter a vector: ' );
count = 0;
for ii = 1:length(x),
if ( x(ii) > 0 ),
count = count + 1;
end
end
fprintf('Number of positive numbers is %d\n', count);
• Find the index of the largest number in a vector
x = input( 'Enter a vector: ' );
max_value = x(1);
max_index = 1;
for ii = 2:length(x),
if ( x(ii) > max_value ),
max_value = x(ii);
max_index = ii;
end
end
fprintf( 'Max value is %d\n', max_value );
fprintf( 'Its index is %d\n', max_index );
• Print a triangle of stars in n rows
n = input( 'Enter the number of rows: ' );
for ii = 1:n,
for jj = 1:ii,
fprintf( '*' );
end
fprintf( '\n' );
end
• Find the kth digit of a number (kth digit from
the right)
num = input( 'Enter the number: ' );
k = input( 'Enter the digit you want: ' );
num_orig = num;
for ii = 1:k,
digit = mod( num, 10 );
num = fix( num / 10 );
end
fprintf('Digit %d of %d is %d\n', k, num_orig, digit);
e.g. solve the following linear equations
• -x1 + x2 + 2x3 = 2
• 3x1 - x2 + x3 = 6
• -x1 + 3x2 + 4x3 = 4
Matlab commands used
• >> A=[-1 1 2; 3 -1 1; -1 3 4]
• >>b=[2;6;4]
• >>x=inv(A)*b
x=1.0000
• -1.0000
• 2.0000
• Or >> x=A\b