Matlab Session 1 Introduction
Matlab Session 1 Introduction
Dr. U D Dwivedi
Assistant Professor (Electrical Engineering)
Room No. 202, Rajiv Gandhi Institute of Petroleum Technology,
Ratapur Chowk,
Rae Bareli -229316 INDIA
Getting Started
MATLAB fundamentals
Index
About Matlab
The basics
Advanced operations
Examples
Advanced Graphics and Plotting
UD Dwivedi
About Matlab
What is Matlab
UD Dwivedi
UD Dwivedi
Construction
Core
Simulation
Simulink
Sig. Proc
C-kernel
Contr. Syst.
m-files
UD Dwivedi
Simulink
8
MATLAB Desktop
10
UD Dwivedi
11
UD Dwivedi
12
13
Working
Memory
Command
Window
Command
History
UD Dwivedi
14
Important
for this course
15
UD Dwivedi
16
Help Window
UD Dwivedi
17
UD Dwivedi
18
19
Running demos
UD Dwivedi
20
21
Uses of MATLAB?
22
Command Window
cd (change directory)
pwd (show the path)
ls (list contents of directory)
whos (list of the variable stored in the memory)
UD Dwivedi
23
Command Window
Getting help from the command window
help <function_name> (show the help document for a given function)
P.S.
If you want to have an help for your own functions, you can write it at
the beginning of the function as :
% your own help.
UD Dwivedi
24
The basics
The Basics
Variables and Arrays
Array: A collection of data values organized into
rows and columns, and known by a single name.
Row 1
Row 2
Row 3
arr(3,2)
Row 4
26
Arrays
27
28
29
Special Values
30
UD Dwivedi
31
32
UD Dwivedi
33
34
>>b = 1:.5:10
c = [1 3 6; 2 7 9; 4 3 1]
The semicolons indicate the end of a row. All rows have to be the
same length.
UD Dwivedi
35
36
Typing "help" at the matlab prompt gives you a list of all the possible directories
matlab can find commands in (which also tells you its "search path", or a list of
the directories it is looking in for commands.)
Typing "help directoryname" gives you a list of the commands in that directory
and a short description of them.
Typing "lookfor keyword" gives you a list of commands that use that keyword. ie,
"lookfor integral" lists commands that deal with integrals. It's pretty slow, choose
the word wisely. You can use control-c to stop searching when you think you've
found what you need.
Typing "doc" starts up a web browser with the Matlab. This includes the entire
reference manual for matlab, a whole lot of other information on using matlab,
and a pointer to the Matlab Primer, a good introduction to using Matlab.
UD Dwivedi
37
UD Dwivedi
38
who
whos
will tell you the variables, their sizes, and some other info.
pi
will tell you all the variables you have currently defined.
eps
UD Dwivedi
39
name for any function in Matlab's search path lets you see
how that function is written.
Check difference between commands help and type
UD Dwivedi
40
Plotting
41
subplot(r,c,n)
will split the plot window into r rows and c columns of plots
and set the current plot to plot number n of those rows and
columns.
title('This is a Title')
xlabel('My X axis')
ylabel('My Y axis')
legend('First Thing Plotted','Second Thing Plotted')
UD Dwivedi
42
0.8
0.6
0.4
0.2
0
10
20
30
40
50
Sampling instants
60
70
80
90
100
60
70
80
90
100
60
70
80
90
100
hold on
subplot(311)
plot(x)
title('Plot of random 100 values')
xlabel('Sampling instants')
ylabel('Random Numbers')
subplot(312)
plot(x,'*k')
title('Plot of random 100 values')
xlabel('Sampling instants')
ylabel('Random Numbers')
subplot(313)
plot(x,'*r')
title('Plot of random 100 values')
xlabel('Sampling instants')
ylabel('Random Numbers')
0.8
0.6
0.4
0.2
0
10
20
30
40
50
Sampling instants
Plot of random 100 values
1
Random Numbers
Random Numbers
0.8
0.6
0.4
0.2
0
10
20
30
UD Dwivedi
40
50
Sampling instants
43
Basic printing
>>print Pprintername
UD Dwivedi
44
load filename.dat
col1 = filename(:,1);
UD Dwivedi
45
save filename.mat
load filename.mat
46
UD Dwivedi
47
Functions
48
49
Global Variables
global phi;
50
Debugging Functions
UD Dwivedi
51
Advanced operations in
Matlab
Variables
UD Dwivedi
53
Complex numbers
Complex scalar
Real part of x
Imaginary part of x
Magnitude of x
Angle of x
Complex conjugate of x
UD Dwivedi
>> x = 3+4j
>> real(x)
>> imag(x)
>> abs(x)
>> angle(x)
>> conj(x)
->3
->4
->5
->0.9273
->3 - 4i
54
Generating vectors
>> x=[a:step:b]
>> x=linspace(a,b,n)
>> x=logspace(a,b,20)
UD Dwivedi
55
Generating matrices
>> A=ones(m,n)
>> A=eye(m,n)
56
>> A=randn(m,n)
>> A=randint(m,n,range)
57
UD Dwivedi
58
+ addition
- subtraction
* multiplication
/ division
^ power
conjugate transpose
UD Dwivedi
59
element-by-element operations
.* multiplication
./ division
.^ power
. transpose (unconjugated)
UD Dwivedi
60
Relational operations
<
<=
>
>=
==
~=
less than
less than or equal to
greater than
greater than or equal to
equal to
not equal to
UD Dwivedi
61
Logical operations
& and
| or
~ not
UD Dwivedi
62
Math functions
cos
acos
cosh
log(natural log)
sqrt
UD Dwivedi
tan
atan
tanh
log10
sign
63
M-files
UD Dwivedi
64
M-files Debug
In Matlab you can debug your m-file, like in other
programming languages
To do it, you need to open your matlab file from the window
command.
Afterwards, you can operate exactly like for other
languages and you can use usual command as:
step in
step out
break point
etc. etc
UD Dwivedi
65
Flow control
Example
If statements
If n<0
a=a-1;
else
a=a+1;
end
if expression
statements
else
statements
end
UD Dwivedi
66
Flow control
For
UD Dwivedi
67
Function in Matlab
To simplify your matlab file structure, you
can use functions. An example of how to
use matlab functions is the following:
Main Matlab Program
a = 10; b = 20;
c = my_sum(a,b);
Function declaration:
function y = my_sum(m,n)
y = m + n ;
return(y) // give the file name of function
same as function name e.g. my_sum.m
UD Dwivedi
68
Entering Matrices
We can enter matrices into MATLAB in several
different ways:
1.
2.
3.
4.
1.
2.
3.
UD Dwivedi
69
70
Interactive Calculations
71
1 2
f
12 13
64
Round-off:
eps = 2-52
Underflow:
realmin = 2-1022
Overflow: realmax = (2-eps) 21023
UD Dwivedi
72
73
74
75
Matrix Operators
76
Indexing Matrices
Indexing
using parentheses
>> A(2,3)
Index
of indices is important!
>> B=A([3 2],[2 1])
>>
B=[A(3,2),A(3,1);A(2,2);A(2,1)]
UD Dwivedi
77
Indexing Matrices
Index
UD Dwivedi
78
Matrix Functions
UD Dwivedi
79
80
Examples
Input
Output
Comments
2+3
7-5
34*212
1234/5786
2^5
ans = 5
ans = 2
Arithmetic works as expected.
ans = 7208
ans = 0.2173 Note that the result is given the name "ans" each time.
ans = 32
a = sqrt(2)
a = 1.4142
UD Dwivedi
82
b = a, pi, 2 + 3i
c = sin(pi)
eps
b = 1.4142
ans = 3.1416
ans = 2.0000 +
3.0000i
c = 1.2246e-016
ans = 2.2204e-016
d=
[1 2 3 4 5 6 7 8 9 d = 1 2 3 4 5 6 7 8 9
e=123456789
]
e = [1:9]
f=123456789
f = 1:9
g = 0:2:10
f(3)
f(2:7)
f(:)
g = 0 2 4 6 8 10
ans = 3
ans = 2 3 4 5 6 7
123456789
UD Dwivedi
83
h = [1 2 3];
h'
(nothing)
ans = 1
2
3
h * h'
h .* h
h + h
ans = 14
ans = 1 4 9
ans = 2 6 8
g = [ 1 2 3;
4 5 6; 7 8 9]
g = 1 2 3
4 5 6
7 8 9
Entering a matrix.
ans = 6
ans = 7 8 9
g = 1 2 3
4 5 4
7 8 9
g(2,3)
g(3,:)
g(2,3) = 4
UD Dwivedi
84
Input
g^2
g .^ 2
Output
Comments
ans =
30 36 42
66 81 96
102 126 150 The first multiplies the matrix by itself.
ans = 1 4 9
The second squares each entry in the
16 25 36
matrix.
49 64 81
UD Dwivedi
85
UD Dwivedi
86
Output
Comments
b=2
b=2
Define b to be a scalar.
a + b
ans = 3 4
5 6
a * b
ans = 2 4
6 8
So does multiplication.
a ^ b
ans = 7 10
15 22
a .^ b
ans = 1 4
9 16
Entry-by-entry power.
UD Dwivedi
87
Vectors
Output
Comments
v = [1 2 3]
u = [3 2 1]
v = 1 2 3
u = 3 2 1
v * u
Error
v * u'
ans = 10
dot(v,u)
ans = 10
cross(v,u)
ans = -4 8 -4
UD Dwivedi
88
UD Dwivedi
89
Transposing Matrices
UD Dwivedi
90
Matrix-Vector Product
91
UD Dwivedi
92
Input
Output
Comments
k = [16 2 3;
5 11 10;
9 7 6]
k = 16 2 3
5 11 10
9 7 6
Define a matrix.
rank(k)
ans = 3
The rank.
det(k)
ans = -136
The determinant.
UD Dwivedi
93
Output
ans =
inv(k)
[vec,val] =
eig(k)
Comments
0.0294 -0.0662 0.0956
-0.4412 -0.5074 1.0662
0.4706 0.6912 -1.2206
UD Dwivedi
Inverse of the
matrix
Eigenvectors
and eigenvalues
of the matrix.
The columns of
"vec" are the
eigenvectors,
and the diagonal
entries of "val"
are the
eigenvaules
94
Input
Output
rand(2)
ans = 0.9501
0.2311
ans = 0.8913
0.7621
rand(2,3)
zeros(2)
ones(2)
ans = 0
0
ans = 1
1
Comments
0.6068
0.4860
0.4565 0.8214
0.0185 0.4447
0
0
1
1
eye(2)
ans = 1 0
0 1
Identity matrix I.
hilb(3)
UD Dwivedi
95
96
Output
[a, a, a]
ans = 1 2 1 2 1 2
3 4 3 4 3 4
[a; a; a]
ans = 1
3
1
3
1
3
2
4
2
4
2
4
ans = 1
3
0
0
2
4
0
0
UD Dwivedi
0
0
1
2
0
0
3
4
97
M - files
98
UD Dwivedi
99
UD Dwivedi
100
101
1.
2.
3.
102
x = a \ b
Try it with
a = [1 2 3; 4 5 6; 7 8 10]; b = [1 1 1]';
x =
-1
1
0
UD Dwivedi
103
104
UD Dwivedi
105
diary '~/session.txt
106
save mysession
load mysession
UD Dwivedi
107
Creating a plot
>> plot(x,y)
produces a graph of y versus x, where x and y are
two vectors
1
0.8
0.6
x=linspace(0,2*pi,100);
plot(x,sin(x));
0.4
0.2
Sine of x
-0.2
-0.4
-0.6
-0.8
-1
UD Dwivedi
109
110
xlabel('string')
ylabel('string')
Title(string)
111
112
Adding plots
0.8
0.6
0.4
plot(x,sin(x));
hold on;
plot(x,cos(x));
xlabel('x');
ylabel('Sine of x');
0.2
Sine of x
-0.2
-0.4
-0.6
-0.8
-1
UD Dwivedi
113
Adding plots
With more graphics
functionalities:
x=linspace(0,2*pi,100);
plot(x,sin(x),-ob);
hold on; grid on;
plot(x,cos(x),->r);
xlabel('x');
ylabel('Sine of x');
legend('sin(x)','cos(x)',3)
UD Dwivedi
114
Plot
Loglog
Semilogx
Semilogy
115
Specialized plots
bar(x,Y)
>> bar((1:1:10),(1:1:10))
UD Dwivedi
116
Specialized plots
Stem
x=linspace(0,2*pi,10);
stem(x,sin(x));
UD Dwivedi
117
Specialized plots
Stairs
x=linspace(0,2*pi,20);
stairs(x,sin(x));
UD Dwivedi
118
Graphics
119
Graphics
Three-dimensional
graphics
>> A = zeros(32);
>> A(14:16,14:16) = ones(3);
>> F=abs(fft2(A));
>> mesh(F)
>> rotate3d on
Several other plot functions available
>> surfl(F)
Can change lightning and material
properties
>> cameramenu
>> material metal
UD Dwivedi
120
Graphics
UD Dwivedi
121
UD Dwivedi
122
MATLAB graphics
The plot function is very powerful for plotting all sorts of variables.
See help plot for more details and see the examples in the MATLAB online tutorial
120
a = 1:100;
b = 100:0.01:101;
c = 101:-1:1;
d = [a b c];
e = [d d d d d];
plot(e)
100
80
60
40
20
200
400
UD Dwivedi
600
800
1000
1200
1400
1600
123
MATLAB graphics
a = 0:0.1:10;
subplot(3,1,1); plot(sin(a))
r1 = rand(1,length(a))*0.2;
subplot(3,1,2); plot(sin(a)+r1)
r2 = rand(1,length(a))*0.8;
subplot(3,1,3); plot(sin(a)+r2)
UD Dwivedi
124
x = rand(1,100);
y = rand(1,100);
plot(x,y,'*')
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
0.1
0.2
0.3
0.4
UD Dwivedi
0.5
0.6
0.7
0.8
0.9
125
MATLAB images
load earth
whos
Name
Size
X
257x250
map
64x3
Bytes Class
514000 double array
1536 double array
UD Dwivedi
126
Thank You!