Introduction to Matlab
Usha B S
[email protected]
What is MATLAB?
2
MATLAB stands for Matrix Laboratory.
MATLAB is a programming environment, a high level
technical computing language, & an interactive environment
for
Algorithm
Development
Numerical
Computation
Usha B S, ECE Dept, RNSIT
Data
Analysis
Data
Visualization
MATLAB
MATLAB is a high-level language and interactive
environment for
Numerical computation,
Data Analysis and Visualization
Acquire, Analyze, Visualize, Document
Programming and Algorithms Development
Integration with Other Languages and
Applications
Application Development and Deployment
3
Usha B S, ECE Dept, RNSIT
MATLAB Toolboxes
MATLAB has a number of add-on software modules, called
toolbox , that perform more specialized computations.
Signal Processing
Image Processing
Communications
System Identification
Wavelet Filter Design
Control System
Fuzzy Logic
Robust Control
-Analysis and Synthesis
LMI Control
Model Predictive Control
Usha B S, ECE Dept, RNSIT
Applications of MATLAB
5
Usha B S, ECE Dept, RNSIT
Applications of MATLAB
6
Usha B S, ECE Dept, RNSIT
Applications of MATLAB
7
Usha B S, ECE Dept, RNSIT
The MATLAB Desktop
8
Current
Folder
View folders
and m-files
Command
Window
Usha B S, ECE Dept, RNSIT
Work Space
type
commands
View
variables
view past
commands
Command
History
The MATLAB System
MATLAB system consists of these main parts:
Desktop Tools and Development Environment
MATLAB desktop and Command Window.
Editor and debugger, code analyzer, Profiler
Browsers for viewing help, the workspace, files, and other
tools
Mathematical Function Library
Usha B S, ECE Dept, RNSIT
How to Resume Default Desktop
10
Usha B S, ECE Dept, RNSIT
Matlab Help
Different ways to find information
help
help general, help mean, sqrt...
helpdesk - an html document with
links to further information
11
Usha B S, ECE Dept, RNSIT
Matlab Help - cont
12
Usha B S, ECE Dept, RNSIT
Setting Fonts
To set custom fonts:
Select File > Preferences > Fonts > Custom.
Select the tool you want to customize from the
Desktop tools list.
The type of font the tool currently uses appears under
Font to Use.
Under Font to Use, select one of the following:
Desktop code.
Desktop text
Custom, and then specify the font characteristics.
Click OK.
13
Usha B S, ECE Dept, RNSIT
MATLAB Variable Names
Variable names ARE case sensitive
Variable names can contain up to 63 characters
Variable names must start with a letter followed
by letters, digits, and underscores.
14
Usha B S, ECE Dept, RNSIT
Variables
No need to declare data type of variables
int a;
double b;
float c;
All variables are created with double precision unless specified and
they are matrices.
Example:
>>x=5;
>>x1=2;
After these statements, the variables are 1x1 matrices with double
precision
15
Usha B S, ECE Dept, RNSIT
Listing & Clearing Variables
a=10
Semicolon suppresses
screen output
b=20;
Avg=(a+b)/2;
whos
Name
Size
a
1x1
avg
1x1
b
1x1
<< clear, clear all
16
Bytes
8
8
8
Class
double
double
double
%clear variables from memory
Usha B S, ECE Dept, RNSIT
Calculations at the Command Line
MATLAB as a Calculator
-5/(4.8+5.32)^2
ans =
-0.0488
a = 2;
b = 5;
a^b
ans =
(3+4i)*(3-4i)
ans =
Semicolon suppresses
screen output
32
x = 5/2*pi;
Results assigned to
ans if name not given
y = sin(x)
25
y =
1
z = asin(y)
z =
Use parentheses ( )
for function inputs
1.5708
Numbers stored in double-precision floating point format
17
Usha B S, ECE Dept, RNSIT
MATLAB Math Operators
Power
Multiplication
Division
or
NOTE:
Addition
Subtraction
Assignment
18
^ or .^ a^b or
a.^b
* (matrix multiply) or
.*(array
a*b
or
a.*b
/ or ./ a/b or
a./b
\ or .\ b\a or
b.\a
56/8 = 8\56
+
a + b
a - b
=
a = b (assign b to a)
Usha B S, ECE Dept, RNSIT
multiply)
Other MATLAB symbols
>>
prompt
...
,
%
;
continue statement on next line
separate statements and data
start comment which ends at end of line
(1) suppress output
(2) used as a row separator in a matrix
specify range
19
Usha B S, ECE Dept, RNSIT
MATLAB Relational Operators
MATLAB supports six relational operators.
Less Than
Less Than or Equal
Greater Than
Greater Than or Equal
Equal To
Not Equal To
20
Usha B S, ECE Dept, RNSIT
<
<=
>
>=
==
~=
MATLAB Logical Operators
MATLAB supports three logical operators.
not
and
or
exor
21
~
&
|
^
Usha B S, ECE Dept, RNSIT
% highest precedence
% equal precedence with or
% equal precedence with and
% equal precedence with and
Worksheet I
22
Usha B S, ECE Dept, RNSIT
Solution-WS1
clc;
clear all;
close all;
A = input('Enter the first point coordinates in square brackets ');
B= input('Enter the second point coordinates in square brackets ');
d = sqrt((A(1)-B(1))^2+(A(2)-B(2))^2);
disp('The distance between given points is');
disp(d);
23
Usha B S, ECE Dept, RNSIT
Matrices & Vectors
24
Usha B S, ECE Dept, RNSIT
Creating Vectors
Order of Matrix M X N
Mno. of rows, N=no. of columns
Vectors - special case
M = 1
N = 1
25
Usha B S, ECE Dept, RNSIT
row vector
column vector
Creating Vectors
A vector is 1-by-n or n-by-1 matrix and appears in
MATLAB as a row or column of real or complex numbers.
We use square brackets to construct vector
26
Usha B S, ECE Dept, RNSIT
Creating Vectors
Create vector with equally spaced intervals
>> x=0:0.5:pi
x = 0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000
Create vector with N equally spaced intervals
>> x=linspace(0, pi, 7)
x =
0 0.5236 1.0472 1.5708 2.0944 2.6180 3.1416
LINSPACE(X1, X2, N) generates N points between X1 and X2.
For N < 2, LINSPACE returns X2.
Equal spaced intervals in logarithm space
x =
>> x=logspace(1,2,7)
10.0000 14.6780 21.5443 68.1292
100.0000
LOGSPACE(X1, X2, N) generates N points between decades
10^X1 and 10^X2.
27
Usha B S, ECE Dept, RNSIT
Transpose
a=[1 2 3];
>> a'
1
2
3
Work Problems of worksheet-II
28
Usha B S, ECE Dept, RNSIT
Working with Matrices
Separate the elements of a row with blanks or commas.
Use a semicolon ; to indicate the end of each row.
Surround the entire list of elements with square brackets, [ ].
A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
MATLAB displays the matrix you just entered:
A=
29
16
5
9
4
3
10
6
15
2
11
7
14
13
8
12
1
Usha B S, ECE Dept, RNSIT
Once matrix is entered , it is
automatically remembered in the
MATLAB workspace and can be
referred to as A.
variable names are case-sensitive
Subscripts
The element in row i and column j of A is given by A(i,j).
So to compute the sum of the elements in the fourth
column of A, we have: A(1,4) + A(2,4) + A(3,4) + A(4,4)
which is same as sum(A(:,4))
30
Usha B S, ECE Dept, RNSIT
Matrix Operations
Enter the Matrix
a=[1 2 3;4 5 6;7 8 9]
a=
1 2 3
4 5 6
7 8 9
Fetching an element in the matrix
a(2,3)
ans =
6
31
Usha B S, ECE Dept, RNSIT
a(3,2)
ans =
8
Accessing Selected Columns and Rows
To read an entire column
colA = matName(:,colNumber)
To read an entire row
varA = matName(rowNumber,:)
Worksheet III
32
Usha B S, ECE Dept, RNSIT
Linear Indexing
2D array can be treated as 1D array, as all the
columns stand together as a single column and
hence specifies single index.
For example, an element at row 1 and column 2
can be specified by linear indexing as
>> MatrixA(5)
33
Usha B S, ECE Dept, RNSIT
34
Usha B S, ECE Dept, RNSIT
Concatenation of Matrices
35
Usha B S, ECE Dept, RNSIT
Generating Vectors (Or Matrices) From Functions
zeros(M,N)
MxN matrix of zeros
ones(M,N)
MxN matrix of ones
rand(M,N)
MxN matrix of uniformly
distributed random
numbers on (0,1)
2. Create a 5x5 unit matrix.
3. Check following commands : eye(3,3)
36
Usha B S, ECE Dept, RNSIT
>> x = zeros(1,3)
x=
0 0 0
>> x = ones(1,3)
x=
1 1 1
>> x = rand(1,3)
x=
0.9501 0.2311 0.6068
Matrices Operations
Given A and B:
Addition
Subtraction
Product
Transpose
* Make sure that the matrices are the same size.
37
Usha B S, ECE Dept, RNSIT
The use of . Element Operation
Given A:
Divide each element of
A by 2
38
Usha B S, ECE Dept, RNSIT
Multiply each
element of A by 3
Square each
element of A
Getting the Size of the Matrix
To get the size of the matrix, use the size
command.
Example: to get the size of matrix a.
[numRow, numCol] = size(a);
39
Usha B S, ECE Dept, RNSIT
Sorting Matrices
To sort a matrix, use the sort command.
Example: sort matrix A in ascending order.
sort(A,ascend)
Sort(A, descend)
Default is ascending mode.
40
Usha B S, ECE Dept, RNSIT
41
Usha B S, ECE Dept, RNSIT
Determine whether array is empty
To Determine whether array is
empty or not, the function
isempty is used
42
Usha B S, ECE Dept, RNSIT
Graphics
MATLAB provides a variety of techniques to display data
graphically.
Interactive tools enable you to manipulate graphs to achieve
results that reveal the most information about your data.
You can also edit and print graphs for presentations, or
export graphs to standard graphics formats for presentation
in Web browsers or other media.
43
Usha B S, ECE Dept, RNSIT
Plot
Example
PLOT Linear plot.
PLOT(X,Y) plots vector
Y versus vector X
PLOT(Y) plots the
columns of Y versus
their index
PLOT(X,Y,S) with plot
symbols and colors
44
Usha B S, ECE Dept, RNSIT
x = [-3 -2 -1 0 1 2 3];
y1 = (x.^2) -1;
plot(x, y1,'bo-.');
Plot Properties
XLABEL X-axis label.
Example
XLABEL('text') adds text
...
xlabel('x values');
ylabel('y values');
beside the X-axis on the
current axis.
YLABEL Y-axis label.
YLABEL('text') adds text
beside the Y-axis on the
current axis.
45
Usha B S, ECE Dept, RNSIT
Hold
HOLD Hold current graph.
HOLD ON holds the current
plot and all axis properties so
that subsequent graphing
commands add to the existing
graph.
Example
hold on;
y2 = x + 2;
plot(x, y2, 'g+:');
HOLD OFF returns to the
default mode
46
Usha B S, ECE Dept, RNSIT
Subplot
SUBPLOT Create axes in tiled positions.
SUBPLOT(m,n,p), or
SUBPLOT(mnp), breaks the Figure
window into an m-by-n matrix of
small axes
x = [-3 -2 -1 0 1 2 3];
y1 = (x.^2) -1;
% Plot y1 on the top
subplot(2,1,1);
plot(x, y1,'bo-.');
xlabel('x values');ylabel('y values');
% Plot y2 on the bottom
subplot(2,1,2);
y2 = x + 2;
Usha B S, ECE Dept, RNSIT
plot(x, y2, 'g+:');
47
Figure
FIGURE Create figure window.
FIGURE, by itself, creates a new
figure window, and returns its handle.
Example
x = [-3 -2 -1 0 1 2 3];
y1 = (x.^2) -1;
% Plot y1 in the 1st Figure
plot(x, y1,'bo-.');
xlabel('x values');
ylabel('y values');
% Plot y2 in the 2nd Figure
figure
y2 = x + 2;
plot(x, y2, 'g+:');
48
Usha B S, ECE Dept, RNSIT
To create a plot of a family of sine curves:
x = [0:.2:20];
y = sin(x)./sqrt(x+1);
y(2,:) = sin(x/2)./sqrt(x+1);
y(3,:) = sin(x/3)./sqrt(x+1);
plot(x,y)
49
Usha B S, ECE Dept, RNSIT
plot(x, y(2,:),'o-', x, y(3,:),'+')
50
Usha B S, ECE Dept, RNSIT
Plotting Multiple Data Sets in One Graph
Multiple x-y pair arguments create multiple graphs with a
single call to plot.
For example:
x = 0:pi/100:2*pi;
y = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
plot(x,y,x,y2,x,y3)
51
Usha B S, ECE Dept, RNSIT
Controlling the Axes
Setting Axis Limits & Grids
The axis command lets you to specify your own
limits: axis([xmin xmax ymin ymax])
You can use the axis command to make the axes
visible or invisible: axis on / axis off
The grid command toggles grid lines on and off:
grid on / grid off
52
Usha B S, ECE Dept, RNSIT
Copying the Figure
53
Usha B S, ECE Dept, RNSIT
Programming in Matlab
Conditional Control
- if, else, elseif
- switch, case
Loop Control
- for, while, continue, break
54
Usha B S, ECE Dept, RNSIT
A simple example:
a=1
while length(a) < 10
a = [0 a] + [a 0]
end
which prints out Pascals triangle:
1
11
121
1331
14641
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
(with a= before each line).
55
Usha B S, ECE Dept, RNSIT
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.
56
Usha B S, ECE Dept, RNSIT
Write the MATLAB statements required to calculate
y(t) from the equation for the values of t between -9
and 9 in steps of 0.5
57
t1 = -9:0.5:9;
i = 1;
for t = -9:0.5:9;
if t>=0
y(1, i) = -3*(t^2)+5;
else
y(1, i) = 3*(t^2)+5;
end
i = i+1;
end
plot(t1,y);
Usha B S, ECE Dept, RNSIT
Use TIC and TOC to measure elapsed time
tic;
for i=1:9000
j=1;
x(i)=j+i;
end
toc
58
Usha B S, ECE Dept, RNSIT
Features-Preallocation
Increases Performance
tic;
tic;
for I = 1:10000
pre_allo =
not_pre_allo(I)=rand(1);
zeros(10000,1);
End
for I = 1:10000
toc
pre_allo(I) =
rand(1);
End
toc
Same resulting vector in both cases:
Preallocating variables creates a contiguous memory
space (10000 elements), at the start
Stops MATLAB from finding 10000 different memory blocks
of 10000 different sizes
59
Usha B S, ECE Dept, RNSIT
Graphics - Overlay Plots
Use hold on for overlaying graphs
hold on;
cub=x.^3;
pl2=plot(x,cub,b-o');
60
Usha B S, ECE Dept, RNSIT
Graphics - Annotation
Use title, xlabel, ylabel and legend for
annotation
>> title('Demo plot');
>> xlabel('X Axis');
>> ylabel('Y Axis');
>> legend([pl1, pl2], 'x^2', 'x^3');
61
Usha B S, ECE Dept, RNSIT
Graphics - Annotation
62
Usha B S, ECE Dept, RNSIT
Graphics-Stem()
stem()is to plot discrete sequence data
The usage of stem() is very similar to
plot()
cos(n/4)
1
n=-10:10;
f=stem(n,cos(n*pi/4))
title('cos(n\pi/4)')
xlabel('n')
0.5
-0.5
-1
-10
63
Usha B S, ECE Dept, RNSIT
-5
0
n
10
Save plots
Use saveas(h,'filename.ext')
to save a figure to a file.
f=figure;
x=-5:0.1:5;
h=plot(x,cos(2*x+pi/3));
title('Figure 1');
xlabel('x');
saveas(h,'figure1.fig')
64
Usha B S, ECE Dept, RNSIT
Useful extension types:
bmp: Windows bitmap
emf: Enhanced metafile
eps: EPS Level 1
fig: MATLAB figure
jpg: JPEG image
m: MATLAB M-file
tif: TIFF image, compressed
Plot Tools
65
Usha B S, ECE Dept, RNSIT
Figure Toolbox
You can open and configure plotting tools in many ways.
To create a figure with the plotting tools attached, use the
plottools command.
You can also start the plotting tools from the figure toolbar
by clicking the Show Plot Tools icon .
66
Usha B S, ECE Dept, RNSIT
The following example shows the plotting tools attached to a
figure containing two subplots of line series data. The code to
produce the graphs is
% First subplot
x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = sin(x+.25);
y3 = sin(x+.5);
subplot(2,1,1);
plot(x,y1,x,y2,x,y3);
axis tight;
67
Usha B S, ECE Dept, RNSIT
% Second sublot
w1 = cos(x);
w2 = cos(x+.25);
w3 = cos(x+.5);
subplot(2,1,2);
plot(x,w1,x,w2,x,w3);
axis tight;
Plot
1
0.5
0
-0.5
-1
1
0.5
0
-0.5
-1
68
Usha B S, ECE Dept, RNSIT
69
Usha B S, ECE Dept, RNSIT
70
Usha B S, ECE Dept, RNSIT
Sound
71
Usha B S, ECE Dept, RNSIT
Play the waveforms
t=0:0.001:5; % 5 secs @ 1kHz sample rate
y1=chirp(t,0,1,150);
%SOUND(Y) plays the sound at the default sample rate of 8192 Hz
sound(y1,8192)
y2=200*sin(20*t)+100*cos(30*t);
sound(y2,8192)
y3=rand(1,8000);
sound(y3,8192)
y4=200*sawtooth(20*t);
sound(y4)
y5=[y1 y2 y3 y4];
Usha B S, ECE Dept, RNSIT
72
sound(y5)
%%Record your voice
Myrec = audiorecorder;
disp('Start speaking.')
recordblocking(Myrec, 5);
disp('End of Recording.');
%%PlayBack
play(Myrec);
%% Store data in double-precision
array.
myRecording = getaudiodata(Myrec);
%% Plot the samples.
plot(myRecording);
73
Usha B S, ECE Dept, RNSIT
Example
lambda=1000; %change to 2000 and see the effect
fs=8000;
f0=1000;
t1=2;
it=(0:fs*t1-1)/fs;
theta=2*pi*it*f0+pi*lambda*(it.^2);
X=cos(theta);
soundsc(X,fs);
74
Usha B S, ECE Dept, RNSIT
Functions
Function with One Output
Define a function in a file named average.m that accepts
an input vector, calculates the average of the values, and
returns a single result.
function y = average(x)
if ~isvector(x)
error('Input must be a vector')
end
y = sum(x)/length(x);
Call the function from the command line.
z = 1:99;
average(z)
75
Usha B S, ECE Dept, RNSIT
Structure of a Function M-file
Keyword: function
Function Name (same as file name .m)
function y = mymean(x)
%MYMEAN Average or mean value.
Online Help
% For vectors, MYMEAN(x) returns the mean value.
% For matrices, MYMEAN(x) is a row vector
% containing the mean value of each column.
[m,n] = size(x);
MATLAB
Code
if m == 1
m = n;
end
y = sum(x)/m;
76
Usha B S, ECE Dept, RNSIT
Function with Multiple Outputs
Define a function in a file named stat.m that returns the
mean and standard deviation of an input vector.
function [m,s] = stat(x)
n = length(x);
m = sum(x)/n;
s = sqrt(sum((x-m).^2/n));
Call the function from the command line.
values = [12.7, 45.4, 98.9, 26.6, 53.1];
[ave,stdev] = stat(values)
ave =
47.3400
stdev =
29.4124
77
Usha B S, ECE Dept, RNSIT
MATLAB Help
MATLAB Help is an
extremely powerful
assistance to learning
MATLAB
Help not only contains the
theoretical background,
but also shows demos for
implementation
MATLAB Help can be
opened by using the
HELP pull-down menu
78
Usha B S, ECE Dept, RNSIT
MATLAB Help (cont.)
Any command description
can be found by typing
the command in the
search field
As shown above, the
command to take square
root (sqrt) is searched
79
Usha B S, ECE Dept, RNSIT
We can also utilize
MATLAB Help from the
command window as
shown
Thank You!!!
Questions??