Matlab
Matlab
1
About Presentation
In this workshop you will learn a few of
the basic functions of MATLAB.
First we will start working with basic
numbers, formats, demos, mathematical
functions, setting variables, matrices and
generating plots by using the plot
functions.
Brief overview of how to generate scripts
in MATLAB called M-files
2
Table of Content
3
Introduction
MATLAB, which stands for Matrix Laboratory, is a
powerful, general-purpose system or environment for
doing mathematics, scientific and engineering
calculations.
MATLAB is matrix-oriented, so what would take
several statements in C or Fortran can usually be
accomplished in just a few lines using MATLAB's built-
in matrix and vector operations.
MATLAB is a "High-Performance Numeric Computation
and Visualization Software" package.
MATLAB is an interactive system whose basic data
is a matrix that does not require dimensioning.
4
Capability of MATLAB
5
Features of MATLAB
6
Uses of MATLAB
7
Basic MATLAB Interface
8
Matlab Window
Command
History
Window
WORKSPACE
WINDOW
Editor Window
Menu and
Toolbar
9
Command Window
10
Workspace Window
11
Command History Window
12
Editor Window
13
Command window: Type your
instructions here and press
ENTER to execute them.
14
Example: Declare a column matrix
with
values 1,2 and 3.
15
Workspace: shows a list of
variables created by MATLAB.
As you can see, the value of ‘aaa’
is shown.
16
Another way to create a variable
Is to press this button.
17
MATLAB will prompt you to enter
the variable name.
18
As you can see, the variable
name has been changed to bbb.
19
2) Or by double clicking
on bbb.
20
When you click on bbb, the variable
editor window appears. You can type
in new values into bbb by filling in the
cells.
21
An example is shown here.
Try and do it yourself.
22
To display variables at the console,
you can type the variable name,
or you can type disp(variable_name).
23
To clear all variables from
memory and close all
figures, use the
clear, close all command.
24
As you can see, all workspace
variables are deleted when
you execute this command.
25
To clear the command window,
use the clc (clear console) command.
26
As you can see, all
console
entries are deleted
when
you execute this
command.
27
.
If you want to see help,
you can type help at the
command window
28
Or you can press F1
to display the help
window. Click on
Open Help Browser
to search for a
specific function.
29
Example: search for
function mean
30
To create new m file
31
The previous command will
display the editor window.
The editor creates an m-file
that can be used to write
your MATLAB programs.
32
To open a exiting m file-
1-Press this button.
Or 2-type open file name
33
To selective text Paste in a m file-
1-Press this button.
Or 2-go to edit and select paste submenu.
3434
To Redo a text in m file-
1-Press this button or
2-go to edit and select redo submenu.
To Redo a text in m file-
1-Press this button.
Or 2-go to edit and select redo submenu.
To undo a text in m file-
1-Press this button.
Or 2-go to edit and select undo submenu.
35
For insert comment in
Matlab.
1)select this option. Or
2) press ctr+r for
selective text
36
For uncomment in
Matlab.
1)select this option. Or
2) Press ctr+T for
selective text.
37
To execute a program, press
the RUN button.
38
This window will appear. Press the
Change Directory button.
39
You can see that the program has
created two new variables in the
Workspace.
40
Debugging
Debug menus
• Set breakpoints to stop the execution of code
>> [i j]=sort2(2,4)
K>>
K>> whos
Name Size Bytes Class
a 1x1 8 double array
b 1x1 8 double array
Grand total is 2 elements using 16 bytes
K>> a
a= local function
2 workspace
K>> return
i=
41
MATLAB - Commands
42
Commands for Managing a Session
43
Commands for Working with the
System
44
Input and Output Commands
45
Format function
46
Vector, Matrix and Array Commands
47
Plotting Commands
48
Command Purpose
49
Data Types Available in MATLAB
50
Data Type Conversion
51
Example of data conversion
Example- 1:
x=3
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
Results:
x=3
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
52
Cont.…..
Example-2:
x = 23.54
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
Reults:
x = 23.5400
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
53
Cont.…..
Example-3
x = [1 2 3]
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
Results:
x=1 2 3
ans = 0
ans = 1
ans = 1
ans = 0
54
Cont.…..
• Example-4
x = 'Hello‘
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
Results:
x = Hello
ans = 0
ans = 0
ans = 1
ans = 0
ans = 0
55
Image Manipulation
56
Reading and Displaying an Image
57
Example: Read and Display Image
58
Manipulating an Image:
Convert to Grayscale:
59
Example: Convert to Grayscale
clear, output:
close all
clc
aaa = imread('D:\DEEPAK
\sun temple\de.jpg');
figure, imshow(aaa)
bbb = rgb2gray(aaa)
figure, imshow(bbb)
60
Image in gray
Image in rgb
61
Saving an Image
• To save an image,
use the imwrite command.
Example:
write image a into file xxx.jpg:
imwrite(A,’xxx.jpg’,’jpg’)
62
MATLAB - Operators
•Arithmetic Operators
•Relational Operators
•Logical Operators
•Bitwise Operations
•Set Operations
63
Arithmetic Operators
64
Cont.…
65
Relational Operators
• Relational operators can also work on both scalar and non-scalar data.
Relational operators for arrays perform element-by-element
comparisons between two arrays and return a logical array of the
same size, with elements set to logical 1 (true) where the relation is
true and elements set to logical 0 (false) where it is not.
66
Logical Operators
Bitwise operator works on bits and performs bit-by-bit operation. The truth
tables for &, |, and ^ are as follows:
68
Set Operations
69
If…else Operator
70
if (condition)
% if block
else
% else block
end
Basic Commands
72
Variables
73
Declaring Single Variables
Example:
var1 = 3;
var2 = 56;
74
Cont.....
75
Cont.....
1var=1;
#var=45;
76
Cont.....
77
Matrix Variables
78
Cont.....
79
Accessing Matrix Values
80
Cont.....
81
Accessing Whole Columns and Rows
mat=[4,5,6,5;1,8,6,2;9,8,4,1;3,2,8,9];
disp(mat)
col3=mat(:,3)
row2=mat(2,:)
82
Cont.....
83
Creating a Matrix of Zeros and Ones
zeromatrix=zeros(6,5)
onesmatrix=ones(6,5)
84
Cont.....
85
Creating a Matrix of Random Numbers
and size of Matrix
To create a matrix of random numbers, use the rand
command.
To get the size of the matrix, use the size command.
Example: create a 7 X 5 matrix of random numbers and
find its colum and row size.
randommatrix=rand(7,5)
[columsize,rowsize]=size(randommatrix);
columsize
rowsize
86
Cont.....
87
Transposing a Matrix
88
Cont.....
89
Cont.....
90
Finding the Maximum and Minimum
Value
To find the maximum value for a matrix, use the max function.
Syntax:
maxVal = max(mat1);
To find the minimum value for a matrix, use the min function.
Syntax:
minVal = min(mat1);
Example:
mat1=[19.12,47.36,48.36;57.36,47.25,79.36;45.36,18.6,19.65]
max(mat1)
max(max(mat1))
mat1=[19.12,47.36,48.36;57.36,47.25,79.36;45.36,18.6,19.65]
min(mat1)
min( min(mat1))
91
Cont.....
92
Cont.....
93
Finding the Sum of Columns
94
Cont.....
95
Adding Matrices
96
Cont.....
97
Subtracting Matrices
98
Cont.....
99
Multiplying Matrices
100
Cont.....
101
Dividing Matrices
102
Cont.....
103
Sorting Matrices
105
Ascending mode
106
Descending mode
107
Ascending and descending of regular
matrix
Example:
mat2=[29.12,37.36,68.36;77.36,47.25,89.36;45.36,98.6,39.65]
sort(mat2,'descend')
sort(mat2,'ascend')
108
Cont.....
109
Flipping a Matrix
110
Cont.....
111
Strings
112
Initializing a String
113
Converting a String to Lowercase
114
Cont.....
115
Converting a String to Uppercase
116
Cont.....
117
Concatenate Strings
118
Cont.....
119
Replace String
To replace part of the string with a new value, use the strrep
command.
Syntax: replace the word ‘Advance Network’ with the word
‘Digital Communication’ in the string string1.
newstring=strrep(string1,’lama’,’baru’)
Example:
string1='M. Tech. in Advance Network'
newstring=strrep(string1,'Advance Network','Digital Communication')
120
Cont.....
121
Line Plot
122
‘xlabel’, ‘ylabel’, and ‘title’
• To label the axes and add title, ‘xlabel’, ‘ylabel’, and ‘title’
functions can be used.
• Example: >> xlabel('string','name','value');
>> ylabel('string','name','value');
>> title('string','name','value');
• String- Text to display as the x-axis label.
• Name- Argument name. Name must appear inside single
quotes (' ').
• Value- Corresponding value.
• We can specify several name and value pair arguments in
any order as Name1,Value1,...,NameN,ValueN.
123
Name-value pair arguments
125
Contd.
126
Legend
127
Location name can be one of the following
strings.
128
Example
129
Contd.
Title
Y label
Legend
Y label
130
Example
• Draw sin(x)
x = 0:pi/36:10*pi;
y = sin(x);
plot(x,y);
131
Contd.
xlabel('x axis','color','red');
ylabel('y axis','color','blue');
Y label
X label
132
Contd.
133
Contd.
legend('sin(x)','location','northeast');
Legend
134
Plotting Multiple Data Sets in One Graph
135
Contd.
Multiple plots
136
Contd.
legend('plot1','plot2','plot3','location','northeast');
Legend
137
Create line plot from Matrix
138
Specifying line color and style
139
Line style
140
Marker style
141
Plotting the lines using line parameters
• Example-
x=1:10;
y=[3 4 2 6 4 5 2 4 5 3];
plot(x,y,'b:v');
xlabel(‘x axis’);
ylabel(‘y axis’);
title(‘Plot’);
legend('plot1','location','northeast');
142
Contd.
Marker style
Line style
143
Multiple plot using line parameter
• Example- x = 0:0.2:10;
y0 = besselj(0,x);
y1 = besselj(1,x);
y2 = besselj(2,x);
y3 = besselj(3,x);
y4 = besselj(4,x);
y5 = besselj(5,x);
y6 = besselj(6,x);
plot(x, y0, 'r+', x, y1, 'go', x, y2, 'b*', x, y3,
'cx',x, y4, 'ms', x, y5, 'yd', x, y6, 'kv');
144
Contd.
Marker style
145
Specify line width, marker size and marker
color
• Example-
x = -pi:pi/10:pi;
y = tan(sin(x)) - sin(tan(x));
plot(x,y,'--gs','LineWidth',2,'MarkerSize',10,
'MarkerEdgeColor','b', 'MarkerFaceColor','r');
146
Contd.
147
Sub plot
148
Contd.
149
Example
150
Contd.
Plot (y)
Plot (y1)
151
Example
152
Contd.
153
Adding Plots to an Existing Graph
154
Example
155
Contd.
Plot of y1
Plot of y2
156
Plotyy
• It is a 2-D line plots with y-axes on both left and right side.
• Baisc format-
plotyy(X1,Y1,X2,Y2);
• It plots X1 versus Y1 with y-axis labelling on the left and
plots X2 versus Y2 with y-axis labelling on the right.
• plotyy(X1,Y1,X2,Y2,function) uses the specified plotting
function to produce the graph.
• plotyy(X1,Y1,X2,Y2,'function1','function2') uses function1
(X1,Y1) to plot the data for the left axis and function2
(X2,Y2) to plot the data for the right axis.
157
Example
158
Contd.
Plot of y1
Plot of y2
159
Example
• Plot two data sets using a graph with two y-axes. Add a title
and axis labels.
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
[HA,hLine1,hLine2] = plotyy(x,y1,x,y2);
title('Multiple Decay Rates');
xlabel('Time (\musec)');
ylabel(HA(1),'Slow Decay');
ylabel(HA(2),'Fast Decay');
160
Contd.
Title
y1 label
y2 label
x label 161
Contd.
• Plot two data sets using a graph with two y-axes. Change
the line styles.
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
[hAx,hLine1,hLine2] = plotyy(x,y1,x,y2);
set(hLine1,'LineStyle','--');
set(hLine2,'LineStyle',':');
162
Contd.
Line style 1
Line style 2
163
Example
• Plot two data sets using a graph with two y-axes. Use a line
plot for the data associated with the left y-axes. Use a stem
plot for the data associated with the right y-axes.
x = 0:0.1:10;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
plotyy(x,y1,x,y2,'plot','stem');
164
Contd.
Line plot
Stem plot
165
Example
• Plot three data sets using a graph with two y-axes. Plot one
set of data associated with the left y-axis. Plot two sets of
data associated with the right y-axis by using two-column
matrices.
x = 0:0.1:10;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
y3 = 0.2*exp(-0.5*x).*sin(10*x);
plotyy(x,y1,[x',x'],[y2',y3']);
166
Example
Plot of y2 Plot of y1
y1 axis
y2 and
y3 axis
Plot of y3
167
Example
• Plot two data sets with different y axes. Plot one data using
semilogarithmic scaling and plot other data using linear
scaling on y axes.
t = 0:900;
z1 = 1000*exp(-0.005*t);
z2 = sin(a*t);
[haxes,hline1,hline2] = plotyy(t,z1,t,z2,'semilogy','plot');
ylabel(haxes(1),'Semilog Plot');
ylabel(haxes(2),'Linear Plot');
xlabel(haxes(2),'Time');
set(hline1,'LineStyle','--','LineWidth',2);
set(hline2,'LineWidth',2);
168
Contd.
Semi log
axes
Linear
axes
169
Plot3
170
Contd.
z axes
x axes
y axes
171
Loglog
• Basic format:
loglog(x,y,LineSpec)
• It plots the y versus x using log scale on both axis.
• Example-
x = logspace(-1,2);
y = exp(x);
loglog(x,y,'-s');
grid on
• grid on adds major grid lines to the current axes.
• grid off removes all grid lines from the current axes.
172
Contd.
Log axes
173
Semilogx
• Basic format:
semilogx(x,y,LineSpec)
• semilogx plot data as logarithmic scales for the x-axis.
• Example-
x = 0:1000;
y = log(x);
semilogx(x,y);
grid on
174
Contd.
Linear axes
Semilog axes
175
Semilogy
• Basic format:
semilogy(x,y,LineSpec)
• semilogy plot data as logarithmic scales for the y-axis.
• Example-
x = 0:0.1:10;
y = exp(x);
semilogy(x,y);
grid on
176
Contd.
Semilog axes
177
Fplot
178
Contd.
Limited by -2 to 2
179
Ezplot
180
Contd.
181
Bar plot
• Example-
Y = [5,2,1 8,7,3 9,8,6 5,5,5 4,3,2];
bar(Y);
182
Contd.
183
Contd.
184
Contd.
185
Contd.
186
Contd.
187
Contd.
188
Pie graph
189
Contd.
190
Contd.
191
Contd.
• To specify the text labels for a pie chart.
• Example- x = 1:3;
labels ={'Taxes','Expenses','Profit'};
pie(x,labels);
192
Contd.
193
Contd.
194
Pie3
195
Contd.
196
Contd.
• To offset the second pie slice, set the corresponding
explode element to 1.
• Example- explode = [0,1,0,0,0];
pie3(x,explode);
197
Area graph
199
Example
200
Contd.
201
Stem plot
202
Example
203
Example
Cos plot
204
Example
• Plot 50 data values of cosine evaluated between 0 and specify the set
of x values for the stem plot.
X = linspace(0,2*pi,50)';
Y = cos(X);
stem(X,Y);
205
Example
Cos plot
206
Example
207
Contd.
208
Example
209
Example
210
Contd.
S(1) subplot
S(2) subplot
211
Stair step graph
212
Example
213
Example
0.5*cos(X)
214
Example
X = linspace(0,4*pi,50)';
Y = [0.5*cos(X), 2*cos(X)];
stairs(X,Y);
215
Example
x1 = linspace(0,2*pi)';
x2 = linspace(0,pi)';
X = [x1,x2];
Y = [sin(5*x1),exp(x2).*sin(5*x2)];
stairs(X,Y);
216
Contd.
exp(x2).*sin(5*x2)
sin(5*x1)
217
Example
• Create a figure with two subplots and return the two axes
handles, s(1) and s(2). Create a stairstep plot in each
subplot by referring to the axes handles.
s(1) = subplot(2,1,1);
s(2) = subplot(2,1,2);
X = linspace(0,2*pi);
Y1 = 5*sin(X);
Y2 = sin(5*X);
stairs(s(1),X,Y1);
stairs(s(2),X,Y2);
218
Contd.
5*sin(X)
sin(5*X)
219
Stem3
220
Example
221
Example
222
Example
• Create a 3-D stem plot and specify the stem locations along
a curve. Use view to adjust the angle of the axes in the
figure.
X = linspace(-5,5,60);
Y = cos(X);
Z = X.^2;
stem3(X,Y,Z);
view(-8,30);
223
Example
• Create a 3-D stem plot with matrix data and specify the
stem locations in the xy-plane.
[X,Y] = meshgrid(0:.1:1);
Z = exp(X+Y);
stem3(X,Y,Z);
224
Example
225
Example
• Create a 3-D stem plot and specify the stem locations along
a circle. Set the stem to a dotted line style, the marker
symbols to stars, and the color to magenta.
theta = linspace(0,2*pi);
X = cos(theta);
Y = sin(theta);
Z = theta;
stem3(X,Y,Z,':*m');
226
Contd.
227
Scatter plot
228
Example
229
Example
230
Example
Small size
filled circles
231
Example
Subplot 2
Subplot 1
Diamond
Circle marker marker
233
Scatter3
234
Example
[X,Y,Z] = sphere(16);
x = [0.5*X(:); 0.75*X(:); X(:)];
y = [0.5*Y(:); 0.75*Y(:); Y(:)];
z = [0.5*Z(:); 0.75*Z(:); Z(:)];
scatter3(x,y,z);
235
Contd.
Z-axis
Y-axis X-axis
236
Example
S = repmat([50,25,10],numel(X),1);
C = repmat([1,2,3],numel(X),1);
s = S(:);
c = C(:);
scatter3(x,y,z,s,c, 'fill');
237
Contd.
238
Polar coordinate plot
239
Example
240
Ezpolar
241
Contd.
242
Contour plot
243
Example
x = linspace(-2*pi,2*pi);
y = linspace(0,4*pi);
[X,Y] = meshgrid(x,y);
Z = sin(X)+cos(Y);
contour(X,Y,Z);
244
Contd.
245
Example
246
Example
• Set up matrices X, Y, and Z. Create a contour plot and
display the contour labels by setting the ‘show text’
property to on.
x = -2:0.2:2; y = -2:0.2:3;
[X,Y] = meshgrid(x,y);
Z = X.*exp(-X.^2-Y.^2);
contour(X,Y,Z,'ShowText','on‘);
247
Example
248
Contourf
249
Contour3
x = -2:0.25:2;
[X,Y] = meshgrid(x);
Z = X.*exp(-X.^2-Y.^2);
contour3(X,Y,Z,30);
250
Contd.
251