Sunteți pe pagina 1din 73

INTRODUCTION TO MATLAB

By
SAMAR JYOTI SAIKIA
DEPT. OF ECE, DBCET

Short Term Course on application of Soft Computing tools in


the field of science and Technology, 2013 (STCSCT2013)

17/6/2013

STCSCT2013

Plan
of
Talk
Introduction

Main Features of MATLAB


MATLAB Desktop
Data types supported by MATLAB
Operators Supported
How to read a matrix?
Elementary Mathematical Functions
2D and 3D Graphics
Generation of m-file
Conclusion
References

17/6/2013

STCSCT2013

Introduction
MATLAB A product by Mathworks is high performance

language for technical computing that integrates


computation, visualization and programming.
MATLAB is developed in the late 1970s by Cleve Moler,
chairman of the computer science department at the
University of New Mexico.
Initially it was developed to perform numerical
calculations on vectors and matrices.
Matlab is now used for mathematical calculations and
simulations in companies and government labs ranging
from aerospace, car design, signal analysis to instrument
control and financial analysis.
17/6/2013

STCSCT2013

The name MATLAB is the combination of two terms,

MATrix LABoratory
Matrices are the basic building blocks in MATLAB
Thus the fundamental numeric data object in
MATLAB is the array.
Vectors, Scalars, real matrices and complex matrices
are all automatically handled as special cases of the
basic data-object.

17/6/2013

STCSCT2013

Main features of MATLAB


The Complete MATLAB set up consists of:
Desktop tools and Development Environment.
Mathematical Function Library.
The language.
Graphics.
External Interfaces.
Documentations.

17/6/2013

STCSCT2013

MATLAB DESKTOP
The MATLAB desktop consists of:
Command Window: Simple basic operations can be done.
Command History: It provides all the details of the

functions typed and codes executed.


Workspace: It includes the names of variable generated
during the running of certain functions and codes.
Current Directory: It shows the location from where the
program is running.
Help Browser: It is the way to go through the details of the
documentation.
17/6/2013

STCSCT2013

17/6/2013

STCSCT2013

Data types Supported By


MATLAB
The data types supported by MATLAB are constant

and variable.
Among variables the supported types are integer,
floating point, character and strings.
The complete list of data types supported by MATLAB
can be generated by typing help datatypes in the
command window.
The simplicity with MATLAB is that, whatever the data
type, users never need to worry about its declaration
i.e. there is no need to declare variables as real or
complex. MATLAB automatically sets the data types of
variables.
17/6/2013

STCSCT2013

Table1: Data types supported by MATAB

17/6/2013

STCSCT2013

Rules for Variable Assignment


Variables in MATLAB are named objects that are
assigned using the equals sign = .
MATLAB variable names must begin with a letter,
which may be followed by any combination of upper
and lowercase letters, digits and underscores.
MATLAB is case sensitive, therefore A and a are
different variables in MATLAB.

17/6/2013

STCSCT2013

10

Although variable names can be of any length,


MATLAB uses only the first N characters of the name
and ignores the rest.
N is the number returned by the function
namelengthmax, which is a built in function in
MATLAB, returns the maximum length allowed for
MATLAB identifiers.
>> N = namelengthmax
N =
63
Hence, it is important to make each variable name
unique in the first N characters to enable MATLAB to
distinguish variables.

17/6/2013

STCSCT2013

11

Variable name should not be same with any


existed function name, otherwise that function is
not allowed to call until the variable is cleared
from memory.
To test whether a proposed variable name is
already used as a function name, user can use the
command,
>> which -all sin
On pressing enter key, a list of m-functions will
be displayed with name sin.
MATLAB uses the characters i and j to represent

imaginary units. Users should avoid using i and j for


variable names if they intend to use them in complex
arithmetic.
17/6/2013

STCSCT2013

12

Operators Supported
MATLAB supported an extensive number of operators.
These are:

Arithmetic Operators

Relational Operators
Logical Operators
Bitwise Operators

Set Operators
17/6/2013

STCSCT2013

13

Arithmetic Operators
MATLAB supports two different types of arithmetic

operations-

i) Matrix arithmetic operations


ii) Array arithmetic operations
Matrix arithmetic operations are defined by the rules
of linear algebra.
Array arithmetic operations are carried out element by
element and can be used with multidimensional arrays
The period character (.) distinguishes the array
operations from the matrix operations.
For on-line help to see arithmetic operators type help
arith.

17/6/2013

STCSCT2013

14

Matrix multiplication.

X*Y is the matrix product of X and Y. Any scalar (a 1-by1 matrix) may multiply anything. Otherwise, the
number of columns of X must equal the number of
rows of Y.
.* Array multiplication
X.*Y denotes element-by-element multiplication. X and
Y must have the same dimensions unless one is a
scalar. A scalar can be multiplied into anything.

17/6/2013

STCSCT2013

15

Relational Operators

Relational operators are used to establish relation

between variables.
Relational operators perform element-by-element
comparisons between two arrays.
They 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.
The operators <, >, <=, and >= use only the real part of
their operands for the comparison.
The operators == and ~= test real and imaginary parts.
For help type help relop.

17/6/2013

STCSCT2013

16

Logical Operators
Logical
operators perform boolean/logical
operation on variables.
The symbols &, |, and ~ are the logical array
operators AND, OR and NOT.
They work element by element on arrays.
It returns logical 0 representing false and logical 1
or any nonzero element representing true.
For help type help relop.

17/6/2013

STCSCT2013

17

Bitwise Operators
Bitwise operators are used to perform bitwise
logical AND, OR, NOT, XOR and shifting
operations.
For help type help ops.

17/6/2013

STCSCT2013

18

Set Operators
MATLAB provides a set of operators for performing set

operations
vectors.

like union, intersection etc. between

For on- line help type help ops

17/6/2013

STCSCT2013

19

How to Read Matrix in MATLAB?


In MATLAB matrix is entered row-wise, with consecutive

elements of a row separated by a space or a comma, and the rows


separated by semicolons or carriage returns.
The entire matrix must be enclosed within square brackets.
Elements of the matrix may be real numbers, complex numbers
or valid MATLAB expressions.
For example,
>> [4 5 6]
ans =
4
5

>> [1 2 3; 4 5 6]
ans =
1
2
3
4
5
6

Vector is a special case of matrix, with just one row or

one column. It is entered the same way as a matrix.


For examples,
>> u=[1 2 3]
u=
1 2 3
u is row vector.
>> v=[1;2;3]
v=
1
2
3
v is a column vector.

If we need to create a vector of numbers over a given

range with a specified increment. MATLAB has a general


command to this as
v=Initial value: Increment: Final value

For example,
>> 0:10:100
ans =
0 10 20 30 40 50 60 70 80 90 100

MATLAB has two built in functions which is most

frequently used to generate vectors:


linspace and logspace

linspace (a,b,n) it generates linearly spaced vector


of length n from a to b.
Logspace (X1, X2, N) - generates a row vector of length N
logarithmically equally spaced points between decades
10^X1 and 10^X2
For example
>> u=linspace(0, 20, 5)
u =
0
5
10
15
20
>> u=logspace(0, 3, 4)
u =
1
10
100
1000

Scalar is matrix with one element i.e. with

dimension 11. A scalar does not need brackets.


For example,
>> g= 2.1
g =
2.1000
Square brackets with no elements between them
create a null matrix. For example,
>> x= [ ]
x =
[ ]

Indexing or Subscripting and Dimensions


User can access the elements of matrix by specifying

their row and column indices.


For example, A(i,j) in MATLAB refers to the element
of the ith row and jth column.
Unlike other software packages and programming
language MATLAB allows the user to specify a range
of rows and columns to specify at the same time.
For example,
A(m:n, k:l) specify rows m to n and column k to
l of matrix A.
A(:,k:l) refers to the elements in the column k
through l of all the rows of matrix A.

MALAB automatically determines the matrix

dimensions.
To check the dimension of an existing matrix user
can use the command
[m,n]=size(A)
it will assign the numbers of rows and columns of
A to the variables m and n respectively.
Command length(A) returns the length of vector
A.
length(A) is equivalent to max(size(A)) for nonempty arrays and 0 for empty ones.

Matrix Handing Operations and Functions


Reshaping Matrices:

1] All the elements of a matrix A can be put into a singlecolumn vector by the command b=A(:).
2] reshape(x, m, n)-Returns the m-by-n matrix
whose elements are taken column wise from x.
An error results if x does not have mn elements.

Transpose of Matrices: Transpose of matrix A is obtained by typing

A.
>> A=[1 2 3; 4 5 6]
A =
1
2
3
4
5
6
>> B=A'
B =
1
4
2
5
3
6

Initialization: Normally initialization is not needed in MATLAB.


1. If a large matrix is to be generated, then a zero matrix of
required dimension is recommended to initialize. It will reserve
a contiguous block for the matrix in the computer memory.
2. Similarly if rows and columns of the matrix are computed in a
loop and appended to the matrix in each execution of the loop,
it is recommended to initialize the matrix to a null matrix
before the loop starts. It will allow the user to append a row or
column of any size.

Appending a row or column: Any row or column can be

easily appended to an existing matrix, provided the row


or column has the same length of the existing matrix.
Example:
A=[A u]- It will append the column vector u to the
columns of A
A=[A ; v]- It will appends the row vector v to the
rows of A.
A row or column of any size can be appended
to a null matrix.
Deleting a row or column: Any row or column of matrix
can be deleted by setting the row or column to a null
vector . Example,
A(2,:)=[ ] - Deletes the 2nd row of matrix A
A(:,3:5)=[ ] - Deletes the 3rd through 5th column
of A

HANDLING MATRICES
Many built in functions are there in MATLAB to create

and manipulate matrices and carry out all the


operations. A few of them are:
X=magic(m): creates a m x m square matrix with
equal row and column and column sums.
A= rand (n) creates a matrix of size n x n of random
values from a uniform distribution.
B= randn(4) creates matrix 4 x 4 containing pseudo
random values from a normal distribution with mean
zero and standard deviation one.
17/6/2013

STCSCT2013

30

C=ones(3) : generates a matrix of size 3 x 3 containing

ones only.
D= zeros(N): generates a matrix of size N x N
containing zeros only.
E= eye(N): generates a identity matrix of size N x N
with ones in the diagonal and zeros every where.

17/6/2013

STCSCT2013

31

ELEMENTATARY MATHEMATICAL
FUNCTIONS
TRIGONOMETRIC FUNCTIONS
EXPONENTIAL FUNCTIONS
COMPLEX
ROUNDING and REMAINDER

In the Command window type help elfun to get the

details of mathematical functions.

17/6/2013

STCSCT2013

32

Some of the trigonomeric


functions:

17/6/2013

sin
sind
sinh
asin
asind
asinh
cos
cosd
cosh
acos
acosd
acosh
tan
tand

- Sine.
- Sine of argument in degrees.
- Hyperbolic sine.
- Inverse sine.
- Inverse sine, result in degrees.
- Inverse hyperbolic sine.
- Cosine.
- Cosine of argument in degrees.
- Hyperbolic cosine.
- Inverse cosine.
- Inverse cosine, result in degrees.
- Inverse hyperbolic cosine.
- Tangent.
- Tangent of argument in degrees.
STCSCT2013

33

Applications of exponential
functions

exp
- Exponential.
expm1
- Compute exp(x)-1 accurately.
log
- Natural logarithm.
log1p
- Compute log(1+x) accurately.
log10
- Common (base 10) logarithm.
log2
- Base 2 logarithm and dissect floating
point number.
pow2
- Base 2 power and scale floating point
number.

17/6/2013

STCSCT2013

34

Use of Complex functions

abs
- Absolute value.
angle
- Phase angle.
complex - Construct complex data from real and
imaginary parts.
conj
- Complex conjugate.
imag
- Complex imaginary part.
real
- Complex real part.
unwrap - Unwrap phase angle.
isreal - True for real array.
cplxpair - Sort numbers into complex conjugate pairs.

17/6/2013

STCSCT2013

35

Rounding and remainder.

fix
floor
ceil
round
mod
division).
rem
sign

17/6/2013

- Round towards zero.


- Round towards minus infinity.
- Round towards plus infinity.
- Round towards nearest integer.
- Modulus (signed remainder after
- Remainder after division.
- Signum.

STCSCT2013

36

Specialized Mathematical functions


To get the details of these functions type help specfun in the command

window.
airy
- Airy functions.
besselj - Bessel function of the first kind.
bessely - Bessel function of the second kind.
besselh - Bessel functions of the third kind (Hankel function).
besseli - Modified Bessel function of the first kind.
besselk - Modified Bessel function of the second kind.
beta
- Beta function.
betainc - Incomplete beta function.
betaln - Logarithm of beta function.
ellipj - Jacobi elliptic functions.
ellipke - Complete elliptic integral.
erf
- Error function.

17/6/2013

STCSCT2013

37

17/6/2013

erfc
- Complementary error function.
erfcx
- Scaled complementary error function.
erfinv - Inverse error function.
expint - Exponential integral function.
gamma
- Gamma function.
gammainc - Incomplete gamma function.
gammaln - Logarithm of gamma function.
psi
- Psi (polygamma) function.
legendre - Associated Legendre function.
cross
- Vector cross product.
dot
- Vector dot product.
STCSCT2013

38

Input and Output Handling in


MATLAB
Input()

X= input( Give the input)


Disp()
If X= Result and disp(the sum is) then disp(x) will show
the string and the result.

17/6/2013

STCSCT2013

39

TWO DIMENSIONAL AND THREE


DIMENSIONAL GRAPHICS
All graphical images are generated in a separate graphics

window".
The main tool of MATLAB graphics is the plot command bearing
syntax,
plot(xvalues, yvalues, `style-options)

where, xvalues: Vectors containing x- coordinate points


yvalues: Vectors containing y-coordinates points
style-option: An optional argument that specifies the
color, the line style, point mark style etc.
The vectors xvalues and yvalues must have the same length.
17/6/2013

STCSCT2013

40

Style Options
There are many style options for changing the

appearance of a plot.
For example:
1. To join the points using a red dash-dotted line.
plot (x,y,r-.)
2. To plot the points using blue crosses without joining
them with lines, and
plot(x,y,bx)
3. To plot the points using blue crosses and joins them
with a blue dotted line.
plot(x,y,b:x)
4. Colors, symbols and lines can be combined.

Color style Option

Line-style Option

red (1 0 0)

g
B
y

green (0 1 0)
blue (0 0 1)
yellow (1 1 0)

-:
-.

m
C
W

magenta (1 0
1)
cyan (0 1 1)
white (1 1 1)

black (0 0 0)

solid line
(default)
dashed line
dotted line
dash-dot
line

Marker-style Option
+

plus sign

O
*
.

circle
asterisk
point

cross

s
d
^

<

square
diamond
upward pointing
triangle
downward pointing
triangle
right pointing
triangle
left pointing triangle

pentagram

hexagram

v
>

TABLE 11: STYLE OPTIONS IN MATLAB

Clearing and Creating the Figure


Window
User can clear the plot window by typing clf, which

stands for clear figure.


To get rid of a figure window entirely, user can type
close.
To get rid of all the figure windows, close all is
used.
New figure windows can be created by typing the
command figure before using the plot command.

Subplots, Labels, Titles, Text and


Legend
Subplot: To plot more than one set of axes in the same

window, subplot command is used.


Syntax:
subplot (m,n,p)
which breaks up the ploting window into m plots in the
vertical direction and n plots in the horizontal direction,
choosing the pth plot for drawing into.

FIGURE 4: DIFFERENT LAYOUT OF SUB FIGURES IN MATLAB

User can put labels, titles and text on a plot by using the

commands:
xlabel(text ) - labels the x-axis with text
ylabel(text ) - labels the y-axis with text
title(text)
- titles the plot with text
text(x,y,text) -places text at position x, y
gtext(text)
- use mouse to place text .

FIGURE 5: AN EXAMPLE OF CREATING SUB FIGURES IN MATLAB

Legend: Legend on plots can be produced using the Insert-

legend button in the figure window toolbar or with the


legend command.
The legend command produces a boxed legend on a plot.
Legend command can take several optional arguments. The
most common commands are listed below:
legend(string1,string2,string3, ...) - Puts
a legend on the current plot using the specified strings as
labels.
legend off- Removes the legend from the current axes
and deletes the legend handle.
legend(h,string1,string2,string3, ...)-Puts
a legend on the plot containing the handles in the vector h
using the specified strings as labels for the corresponding
handles.

>> n=1:10;

x1=log(n);

% fun_1

x2=log10(n);

% fun_2

x3=5*exp(-n);

% fun_3

x4=rand(1,length(n)); % fun_4
plot(n,x1,'-ro',n,x2,'-.b',n,x3,'-k',n,x4,'om'),
title('plot with legend'),
legend('fun_1','fun_2','fun_3','fun_4');

Axis:
In MATLAB once plot is generated axis function can be used to
change axis limits.
Syntax:
axis([xmin xmax ymin ymax])
xmin, ymin- Minimum values for x-axis and y-axis
xmax, ymax- Maximum values for x-axis and y-axis
There are also some useful predefined string arguments for the axis

command:

axis(equal)- sets equal scale on both axes


axis(square)- sets the default rectangular frame to a square
axis(normal)- resets the axis to default values
axis(axis)- freezes the current axes limits
axis(off)- removes the surrounding frame and the tick marks

The axis command must come after the plot

command to have the desired effect.


At times it is possible to control a part of the axes

limits and let MATLAB set the other limits


automatically.
For example,
axis([-5 10 inf inf])
axis([-5 inf -inf 22])
17/6/2013

STCSCT2013

53

Overlay plots:
MATLAB provides three different commands of generating overlay plots.
1. hold command.

2. line command.
3. plot command itself.

Syntax:
hold- Hold current graph
hold on- Holds the current plot and all axis properties so that
subsequent graphing commands add to the existing graph.
hold off- returns to the default mode whereby PLOT commands erase
the previous plots and reset all axis properties before drawing new plots.
line(x,y)- adds the line in vectors X and Y to the current axes.

Three-Dimensional
Plots
The plot3 command is used for visualizing three-dimensional

graphics.
Syntax:

plot3(x,y,z)
where x, y and z are three vectors of the same length, plots a line in
3-space through the points whose coordinates are the elements of x,
y and z.
Plots in 3-D can be annotated with functions already mentioned for 2D plots like xlabel, ylabel, title, text etc.
MATLAB provides a very important command view to specify the
viewing angle for an observer.
Syntax:
view(az,el)
where, argument az is the azimuth angle and el is the elevation angle.

17/6/2013

STCSCT2013

55

>> t=0:pi/70:15*pi;
f1=sin(t);
f2=cos(t);
figure, subplot(2,2,1);plot3(f1,f2,t); grid on;
axis square;
xlabel('sin(t)');ylabel('cos(t)');zlabel('t');
title('A circular helix');
subplot(2,2,2);plot3(f1,f2,t);view(0,90);
xlabel('sin(t)');ylabel('cos(t)');
title('projection in the X-Y plane');
subplot(2,2,3);plot3(f1,f2,t);view(0,0);
xlabel('sin(t)');ylabel('cos(t)');
title('projection in the X-Z plane');
subplot(2,2,4);plot3(f1,f2,t);view(90,0);
xlabel('sin(t)');ylabel('cos(t)');
title('projection in the Y-Z plane');

Plotting Discrete Data


At times it may be required to generate graphics of discrete data, most

frequently in applications involving digital signal processing. In such


cases, MATLAB command stem can be used in the same manner as
command plot.
Syntax,
stem(x,y)
It generates a plot of discrete sequence y at the values specified in x
terminated by a circle.
In order to visualize discrete 3-D graphics MATLAB stem3 command
can be used
Syntax,
stem3(x,y,z)

17/6/2013

STCSCT2013

57

>> t=linspace(-2*pi,2*pi,20);

>> x=linspace(0,0.5,8);

x=tan(cos(t1));

y=x*0.75;

figure, stem(t1,x1);

z=2*sin(x)+3*cos(y);

title('use of stem');

stem3(x,y,z);

xlabel('t');ylabel('tan(cos(t))');

title('3-D discrete plot');

FIGURE 8: USE OF stem COMMAND

Use of BAR, HIST and STAIR


Generally three commands are used to present data in

graphics.
bar command
hist command
stair command
MATLAB command bar is used to present data in vertical
columns.
Syntax
bar(x,y)
It draws the columns of the M-by-N matrix y as M groups of
N vertical bars. The vector X must not have duplicate values.

Another command hist can be used to generate histogram,

which is a type of bar graphs that are created by first specifying


the number of levels that specify a range of values and then
counting the number of occurrences of a data set that fall within
each level.
Syntax
hist(y)
If y is a vector with 10 values, it will create a histogram with 10
equally spaced bins that cover the range of values between the
minimum and maximum values of the variable y.
Similarly, a stair plot may be used to stress the discrete nature of a
data set. The functions stairs(y) or stair(x, y) can be used to draw
horizontal lines at the level specified by the elements of y. This
level will be held constant over the period between the values
specified by the index numbers when using stairs(y) or the
elements in x when using stairs(x,y).

>> n=1000
>> x=[1 4 6 8]
y= [5 2;5 4;3 4; 3.5 3]
figure, bar(x, y),
title('Bar plot')

beta=1.5
y=-beta*log(rand(1,n))
x=0.2:0.4:10
figure, hist(y,x),
ylabel('count'),

>> a
=linspace(0,2*pi,30);

b=linspace(2*pi,4*pi,30);
x=[a b];
figure, stairs(x,sin(x))
title('Stair plot');

title(' Histogram')

Figure 9: Use of bar, hist and plot


command

Generation of m-file

Generation of m-FILE
It is already known that using command prompt we

can solve a problem. But the command prompt has


many limitations.
The limitations are--- Only the shorter code can be written.
There is no possibility of modification in the codes.

Executed program in the command prompt cant

store for manipulation or modification .

NEED OF M-FILE CREATION

The solution of these problem is to use matlab

editor.
In matlab editor we can write the codes and the
codes can be modified in the time of writing or
later.
Store the executed files.
Generate the user defined function which
reduces the code complexity and code
redundancy in the main program.

Matlab Editor
The editor is a platform in the Matlab package by

which programs can be written, modified and stored


very easily.
Using the editor, the programmer can generate the

Matlab executable m-file.

Matlab Editor

Universal Codes for M-files


There are certain codes which are always written in

m-file irrespective of programming problem. Those


codes are given below clc
clear all
close all

Universal Codes for M-files


Code

Function

clc

Clear the contents of command prompt.

clear all

clear variables and functions from memory and workspace.

close all

close all the open figure window.

Precaution while saving the m-file

Name of the file should not start with special


characters like _, @, & , %, # etc.

M-file name should not be similar to the built-in

functions.
Space is not allowed in the m- file name.

Generation of m-file

Conclusion
Now a days MATLAB is used in every field of research

or in labs or in industry.
The basic component which MATLAB deals with is the
matrix.
Whatever the field of application, MATLAB converts
all the data into matrix or matrix arrays.
We have discussed briefly the introduction of matlab,
data types used, different types of operators it
supports.
We have also discussed how to create an m-file.

17/6/2013

STCSCT2013

71

References
Sarma, K.K. (2010), MATLAB Demystified, Basic

concept and Applications, Vikash Publication.


Pratap R. , Getting Started with MATLAB 7, Oxford
University Press.

17/6/2013

STCSCT2013

72

Thank You

17/6/2013

STCSCT2013

73

S-ar putea să vă placă și