Вы находитесь на странице: 1из 71

INTRODUCTION TO

MATLAB

1
2
The name MATLAB stands for
MATrix LABoratory.
MATLAB is a high-performance
language for technical computing. It
integrates
computation, visualization, and
programming environment.

3
Matlab is a program for doing
numerical computation. It was
originally designed for solving linear
algebra type problems using matrices.

Matlab is also a programming language


that currently is widely used as a
platform for developing tools for
Machine Learning.

4
Some other aspects of Matlab
Matlab is an interpreter -> not as fast as compiled
code
Typically quite fast for an interpreted language
Often used early in development -> can then
convert to C (e.g.,) for speed
Can be linked to C/C++, JAVA, SQL, etc
Commercial product, but widely used in industry
and academia
Many algorithms and toolboxes freely available

5
Starting MATLAB

you can enter MATLAB by double-clicking on


the MATLAB shortcut icon (MATLAB 7.0.4) on
your Windows desktop. When you start
MATLAB, a special window called the MATLAB
desktop appears. The desktop is a window that
contains other windows.

6
Matlab Screen
Command Window
type commands

Current Directory
View folders and m-files

Workspace
View program variables
Double click on a variable
to see it in the Array Editor

Command History
view past commands
save a whole session
using diary

7
Expression
Numbers
MATLAB uses conventional decimal notation, with an optional
decimal point and leading plus or minus sign, for numbers.
Scientific notation uses the letter e to specify a power-of-ten
scale factor. Imaginary numbers use either i or j as a suffix.
Some examples of legal numbers are
3 -99 0.0001 9.6397238 1.60210e20
6.02252e231i -3.14159j 3e5i

8
MATLAB Math & Assignment Operators

Power ^ or .^ a^b or a.^b


Multiplication * or .* a*b or a.*b
Division / or ./ a/b or a./b
or \ or .\ b\a or b.\a
NOTE: 56/8 = 8\56

Addition + a+b
Subtraction - a-b
Assignment = a=b (assign b to a)

9
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 ~=

10
MATLAB Logical Operators

MATLAB supports three logical operators.

not ~ % highest precedence


and & % equal precedence with or
or | % equal precedence with and

11
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

12
Hierarchy of arithmetic operations

Precedence Mathematical operations

First The contents of all parentheses are evaluated


first, starting from the innermost
parentheses and working outward.
Second All exponentials are evaluated, working from
left to right
Third All multiplications and divisions are
evaluated, working from left to right
Fourth All additions and subtractions are evaluated,
starting from left to right

13
Variables

Have not to be previously declared


Variable names can contain up to 63
characters
Variable names must start with a letter
followed by letters, digits, and underscores.
Variable names are case sensitive

14
MATLAB Special Variables

ans Default variable name for results


pi Value of
eps Smallest incremental number
inf Infinity
NaN Not a number e.g. 0/0
i and j i = j = square root of -1
realmin The smallest usable positive real number
realmax The largest usable positive real number

15
Expression
Functions
MATLAB provides a large number of standard elementary
mathematical functions, including abs, sqrt, exp, and sin. For a
list of the elementary mathematical functions, type :
help elfun
For a list of more advanced mathematical and matrix functions,
type:
help specfun
help elmat

16
17
HELP

Within Matlab
Type help at the Matlab prompt or help
followed by a function name for help on a
specific function
Online
Online documentation for Matlab at the
MathWorks website
http://www.mathworks.com/access/helpdesk
/help/techdoc/matlab.html
There are also numerous tutorials online that
are easily found with a web search.
18
Array, Matrix
a vector x = [1 2 5 1]

x=
1 2 5 1

a matrix x = [1 2 3; 5 1 4; 3 2 -1]

x=
1 2 3
5 1 4
3 2 -1

transpose y = x y=

19
Long Array, Matrix
t =1:10

t=
1 2 3 4 5 6 7 8 9 10
k =2:-0.5:-1

k=
2 1.5 1 0.5 0 -0.5 -1

B = [1:4; 5:8]
x=
1 2 3 4
5 6 7 8

20
MATLAB Matrices

A matrix with only one row is called a row vector. A row


vector can be created in MATLAB as follows (note the
commas):

EDU rowvec = [12 , 14 , 63]

rowvec =

12 14 63

21
MATLAB Matrices

A matrix with only one column is called a column vector. A


column vector can be created in MATLAB as follows (note the
semicolons):

EDU colvec = [13 ; 45 ; -2]

colvec =

13
45
-2

22
MATLAB Matrices

A matrix can be created in MATLAB as follows (note the commas


AND semicolons):

EDU matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]

matrix =

1 2 3
4 5 6
7 8 9

23
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

24
Operators (arithmetic)
+ addition
- subtraction
* multiplication
/ division
^ power
complex conjugate transpose

25
Matrices Operations

Given A and B:

Addition Subtraction Product Transpose

26
Some powerful matrix functions in Matlab

X = A % Transposed matrix
X = inv(A) % Inverse matrix squared matrix
X = pinv(A) % Pseudo inverse
X = chol(A) % Cholesky decomp.
d = det(A) % Determinant
[X,D] = eig(A) % Eigenvalues and
eigenvectors
[Q,R] = qr(X) % QR decomposition
[U,D,V] = svd(A) % singular value decomp.

27
Operators (Element by Element)

.* element-by-element multiplication
./ element-by-element division
.^ element-by-element power

28
Scalar - Matrix Addition

EDU a=3;
EDU b=[1, 2, 3;4, 5, 6]
b=
1 2 3
4 5 6
EDU c= b+a % Add a to each element of b
c=
4 5 6
7 8 9

29
Scalar - Matrix Subtraction

EDU a=3;
EDU b=[1, 2, 3;4, 5, 6]
b=
1 2 3
4 5 6
EDU c = b - a %Subtract a from each element of b
c=
-2 -1 0
1 2 3

30
Scalar - Matrix Multiplication

EDU a=3;
EDU b=[1, 2, 3; 4, 5, 6]
b=
1 2 3
4 5 6
EDU c = a * b % Multiply each element of b by a
c=
3 6 9
12 15 18

31
Scalar - Matrix Division

EDU a=3;
EDU b=[1, 2, 3; 4, 5, 6]
b=
1 2 3
4 5 6
EDU c = b / a % Divide each element of b by a
c=
0.3333 0.6667 1.0000
1.3333 1.6667 2.0000

32
The use of . Element Operation
A = [1 2 3; 5 1 4; 3 2 1]
A=
1 2 3
5 1 4
3 2 -1

b = x .* y c=x./y d = x .^2
x = A(1,:) y = A(3 ,:)
b= c= d=
x= y= 3 8 -3 0.33 0.5 -3 1 4 9
1 2 3 3 4 -1
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.

33
Evaluate expressions using MATLAB :

Exercise1 :

34
35
Exercise 2 :

36
37
Exercise 3,4 :

38
Exercise 5 :

39
2-D Plots
Exercise 6 :
Example:
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)

Now label the axes and add a title. The characters \pi
create the symbol pi.
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)

40
Dr. Keshav Patidar 40
Multiple Data Sets in One Graph
Multiple x-y pair arguments create multiple graphs
with a single call to plot.
MATLAB automatically cycles through a predefined
(but user settable) list of colors to allow discrimination
between each set of data.
Exercise7 :
For example, these statements plot three related
functions of x, each curve in a separate
distinguishing color.
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)
The legend command provides an easy way to identify
the individual plots.
legend('sin(x)','sin(x-.25)','sin(x-.5)')
Dr. Keshav Patidar 41
Specifying Line Styles and Colors
It is possible to specify color, line styles, and markers
(such as plus signs or
circles) when you plot your data using the plot
command.
plot(x,y,'color_style_marker')
color_style_marker is a string containing from one to
four characters
(enclosed in single quotation marks) constructed
from a color, a line style, and a marker type:

Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'.
These correspond
to cyan, magenta, yellow, red, green, blue, white, and
Dr. Keshav Patidar 42
black.

Dr. Keshav Patidar 43


Line style strings are '-' for solid, '--' for dashed, ':'
for dotted, '-.' for dash-dot. Omit the line style for no
line.

The marker types are '+', 'o', '*', and 'x' and the
filled marker types 's for square, 'd' for diamond,
'^' for up triangle, 'v' for down triangle, '>'for right
triangle, '<' for left triangle, 'p' for pentagram, 'h' for
hexagram,
and none for no marker.

Dr. Keshav Patidar 44


Plotting Lines and Markers
If you specify a marker type but not a line-style, MATLAB
draws only the marker. For example,
plot(x,y,'ks')
plots black squares at each data point, but does not connect
the markers with a line.
The statement
plot(x,y, 'r:+')
plots a red dotted line and places plus sign markers at each
data point. You may want to use fewer data points to plot the
markers than you use to plot the lines. This example plots the
data twice using a different number of points for the dotted
line and marker plots.
Exercise 8 :
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
Dr. Keshav Patidar 45
Dr. Keshav Patidar 45
Imaginary and Complex Data
When the arguments to plot are complex, the imaginary part
is ignored except
when plot is given a single complex argument. For this
special case, the
command is a shortcut for a plot of the real part versus the
imaginary part.
Therefore,
plot(Z)
where Z is a complex vector or matrix, is equivalent to
plot(real(Z), imag(Z))

Exercise9 :
t = 0:pi/10:2*pi;
plot(exp(i*t),'-o')
draws a 20-sided polygon with little circles at the vertices.
Dr. Keshav Patidar 46
Dr. Keshav Patidar 47
Adding Plots to an Existing Graph
The hold command enables you to add plots to
an existing graph. When you type
hold on

MATLAB does not replace the existing graph


when you issue another plotting command;

it adds the new data to the current graph,


rescaling the axes if necessary.

Dr. Keshav Patidar 48


Multiple Plots in One Figure
The subplot command enables you to display
multiple plots in the same window or print them
on the same piece of paper. Typing

subplot(m,n,p)

partitions the figure window into an m-by-n


matrix of small subplots and selects the p-th
subplot for the current plot.
The plots are numbered along first the top
row of the figure window, then the second row,
and so on.
Dr. Keshav Patidar 49
Setting Axis Limits
By default, MATLAB finds the maxima and
minima of the data to choose the
axis limits to span this range. The axis command
enables you to specify your own limits

axis([xmin xmax ymin ymax])

Use the command


axis auto
to re-enable MATLABs automatic limit
selection.

Dr. Keshav Patidar 50


Setting Axis Aspect Ratio
axis also enables you to specify a number of predefined
modes. For example,
axis square
makes the 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. This means
plot(exp(i*[0:pi/10:2*pi]))
followed by either axis square or axis equal turns the
oval into a proper circle.
axis auto normal
returns the axis scaling to its default, automatic mode.

Dr. Keshav Patidar 51


Setting Axis Visibility
You can use the axis command to make the axis visible
or invisible.
axis on
makes the axis visible. This is the default.
axis off
makes the axis invisible
Setting Grid Lines
The grid command toggles grid lines on and off. The
statement
grid on
turns the grid lines on and
grid off
turns them back off again.
Dr. Keshav Patidar 52
Using Plot Editing Mode

The MATLAB figure window supports a point-and-


click style editing mode that
you can use to customize the appearance of your
graph.

Dr. Keshav Patidar 53


Exercises 10:
1. Evaluate the function
y =x/(x+(1/x^2))
for x = 3 to x = 5 in step of 0.01 and make its plot.
2. Plot the function y (t)= ( 1-e^(2.2 t ) cos 60t .
Use t from 0 to 0.25 in 0.001 increments.
3. Let be the function y = sin(x^2); x [0; 2]
make a simple plot with x=[0:2*pi] (plot(x,y)),
try making the step smaller,
add some labels (xlabel, ylabel),
and a title (title),
and a legend (legend),
add a grid (grid on).
Type help plot and use the information to change
color and marker. Dr. Keshav Patidar 54
4. Add the functions p = 3sin(x^2 )+ 2cos(y^3 ) and
q = 3cos(y)+ 2y^2 for x in the range 0 to 5.
y = 0.05x + 2.01 in all cases. Use increments of 0.01.
Plot all three functions on same figure and use suitable
labels, titles and legend.

5. The complex function f(t) has the form: f( t) =3e^(-


j2t + / 4 ).
Plot the real and imaginary parts as a function of time
from 0 to 3 seconds in 0.01-second increments using
subplot command and on same axis use suitable labels,
titles and legend.

Dr. Keshav Patidar 55


3-D Plots
Command used:

Plot(x, y, z)

Where x, y and z are equal sized array

Plot3(x, y, z)

Dr. Keshav Patidar 56


Exercise 11: Plot 3-D line plot, consider the
following functions:

X(t)= (e^(-0.2t))cos2t
Y(t)= (e^(-0.2t))sin2t

Where t range is 0 to 10, use suitable labels, titles


and legend.

Dr. Keshav Patidar 57


Stem Plots
Command used:
x=[ 1 2 3 4 5 6];
y=[2 4 5 6 2 8];
stem(x, y)

0
1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6

Dr. Keshav Patidar 58


Bar Plots
Commands used:
x=[ 1 2 3 4 5 6];
y=[2 4 5 6 2 8];
bar(x, y)

0
1 2 3 4 5 6

Dr. Keshav Patidar 59


Stair Plots
Commands used:
x=[ 1 2 3 4 5 6];
y=[2 4 5 6 2 8];
stairs(x, y)

0
0 1 2 3 4 5 6

Dr. Keshav Patidar 60


Pie Plots
Commands used:
x=[ 1 2 3 4 5 6];
pie(x)
y=[2 4 6 8 3 1]
Pie(y)
5%

10%

29%

14%

19%
24%

Dr. Keshav Patidar 61


Compass Plots
Commands used:
x=[ 1 2 3 4 5 6];
y=[2 4 5 6 2 8]; 90
10
compass(x, y) 120
8
60

6
150 30
4

180 0

210 330

240 300

270

Dr. Keshav Patidar 62


Exercise 12: Plot the function

y= (e^(-x))sin(x)
Where x range is 0 to 2 in steps of 0.1. create the
following plot types (a) stem plot, (b) stair plot, (c)
bar plot, (d) compass plot. Use suitable labels,
titles and legend.

Dr. Keshav Patidar 63


Mesh Plots
Commands used:
[x, y]= (-2:0.1:2);
z=exp(-0.2*(x.^2+y.^2));
mesh(x, y, z)

0.8

0.6

0.4

0.2
2
1 2
0 1
0
-1 -1
Dr. Keshav Patidar 64
-
2
-2

Dr. Keshav Patidar 65


surface Plots
Commands used:
[x, y]= (-2:0.1:2);
z=exp(-0.2*(x.^2+y.^2));
surf(x, y, z)

0.8

0.6

0.4

0.2
2
1 2
0 1
0
-1 -1
-2 -2

Dr. Keshav Patidar 66


Exercise: Plot 3-D line plot for the function v(t)

v(t)= 10e^(-0.2+j)t
Where t range is 0 to 10, use command plot3,
where the three dimensions are the real part,
imaginary part of function and time. Use suitable
labels, titles and legend.

Dr. Keshav Patidar 67


Exercise 13: Plot 3-D mesh and surface plot for the
function

z(t)= e^(x+jy)
Where x range is -1 to 1, and y range is -2pi to
2pi.plot real part of z versus x and y. Use suitable
labels, titles and legend.

Dr. Keshav Patidar 68

Вам также может понравиться