Post on 14-Apr-2018
7/30/2019 MATLAB-Introduction to Applications
1/62
MATLAB
Introduction to Applications
Prasanta Sarkar
National Institutes of Technical Teachers
Training and Research, Kolkata
7/30/2019 MATLAB-Introduction to Applications
2/62
Introduction to MATLAB
MATLAB is a high performance language for
technical computing. It integrates
computation, visualization, and programming.Typical uses include :
Math and computation
Algorithm development
7/30/2019 MATLAB-Introduction to Applications
3/62
Introduction to MATLAB
Data acquisition Modeling, simulation, and
prototyping
Data analysis, exploration, and visualization
Scientific and engineering graphics
Application development, including
graphical user interface building
7/30/2019 MATLAB-Introduction to Applications
4/62
Introduction to MATLAB
The MathWorks
Product Family
MATLAB
computational language,
Math and Visualization
SIMULINKGraphical Modelling,
simulation of continuous
and discrete systems
STATEFLOWSimulation of event
driven systems to
complement Simulink
7/30/2019 MATLAB-Introduction to Applications
5/62
The MATLAB System
The MATLAB system consists of five main parts:
1. Development Environment: Set of tools and
facilities that help to use MATLAB functions and
files. Many of these tools are graphical user
interfaces. It includes the MATLAB desktop and
Command Window, a command history, an editor
and debugger, and browsers for viewing help, the
workspace, files, and the search path
7/30/2019 MATLAB-Introduction to Applications
6/62
The MATLAB System
2. Mathematical Function Library: Vast
collection of computational algorithms ranging
from elementary functions, like sum, sine,cosine, and complex arithmetic, to more
sophisticated functions like matrix inverse,
matrix eigenvalues, Bessel functions, and fast
Fourier transforms.
7/30/2019 MATLAB-Introduction to Applications
7/62
The MATLAB System
3. The Language: This is a high-level
matrix/array language with control flow
statements, functions, data structures,input/output, and object-oriented programming
features.
4. Graphics: Facilities for displaying vectors and
matrices as graphs. Two-dimensional and three-
dimensional data visualization, image processing,
animation, and presentation as well as to build
complete graphical user interfaces.
7/30/2019 MATLAB-Introduction to Applications
8/62
The MATLAB System
5. Application Program Interface (API): This is
a library that allows to write C and Fortran
programs that interact with MATLAB. It includesfacilities for calling routines from MATLAB
(dynamic linking), calling MATLAB as a
computational engine, and for reading and writing
MAT-files
7/30/2019 MATLAB-Introduction to Applications
9/62
Starting a MATLAB Session
Start a MATLAB Session from Desktop of acomputer
Click Start Button
All Programs
MATLAB 7.0.1
OR, Click MATLAB
icon on Desktop
7/30/2019 MATLAB-Introduction to Applications
10/62
MATLAB Environment
Major components of MATLAB environment:
Command Window
Command History
Workspace
Current Directory
Figure Window
Edit Window
7/30/2019 MATLAB-Introduction to Applications
11/62
MATLAB Environment
Default Desktop of MATLAB
Workspace
WindowCommand
Window
Command
History
Window
7/30/2019 MATLAB-Introduction to Applications
12/62
MATLAB Environment
Execute the following statements using plot command
to get the Figure Window
x=0: 0.05: 30;y=cos (x);
plot (x, y)
FigureWindow
7/30/2019 MATLAB-Introduction to Applications
13/62
Types of files
M-files - script & function files
script file : An M-file (with .m extension) with a setof MATLAB commands is called a script file which
may include user defined or built-in functions.
function file : An M-file beginning with a function
definition line is a function file which is run by
entering its name.
7/30/2019 MATLAB-Introduction to Applications
14/62
Types of files
MAT-filesThese are binary data-files saved as *.mat file fromworkspace data and loaded into workspace by load
commandMDL-files
These are saved as *.mdl file for graphical extensionof MATLAB using simulink blocks
MEX-filesThese are FOTRAN / C programs (*.mex) callable byMATLAB to integrate code with it.
7/30/2019 MATLAB-Introduction to Applications
15/62
Evaluating expression
command window displays a command prompt >>
and a cursor
Enter expression50*2 - 30/2 + 5
at the cursor
Push enter key
The result isstored in default
variable ans
7/30/2019 MATLAB-Introduction to Applications
16/62
Creating and Saving M-file
Execute expression x=5, y=x+6, z=x+2*y
Select expression
in History Window Right click on it
Click create M-file
Edit Window will
pop up Save the file (with
.m extension) in
the Directory
C:\MATLAB7\work
Edit Window
7/30/2019 MATLAB-Introduction to Applications
17/62
Execute a command
Execute the command
who or whos
It display currently used
variables as
Your variables are:
A ans x y z
Note that semi-colon(;)
after expression
do not display result
>> 50*2-30/2+5; x=5; y=x+6; z=x+2*y;
>> A=[1 4;2 5;3 6]'
A =
1 2 3
4 5 6
>> who
Your variables are:
A ans x y z
>> whos
Name Size Bytes Class
A 2x3 48 double array
ans 1x1 8 double array
x 1x1 8 double array
y 1x1 8 double array
z 1x1 8 double array
Grand total is 10 elements using 80 bytes
7/30/2019 MATLAB-Introduction to Applications
18/62
Some MATLAB Commands
General Commands
clock - provide clock and time as a vector
date - provide a date string
ver - provide version of MATLAB
Directory Commands
pwd - present working directory
cd - change present working directory
dir / ls - list files/folders of current directory
path - display MATLAB search path
editpath - modify MATLAB search pathWorkspace Commands
who / whos - variables currently in workspace
what - list types of files .m, .mat, .mex
7/30/2019 MATLAB-Introduction to Applications
19/62
Some MATLAB Commands
Workspace Commands
clear all - clear the variables on workspace
mlock fun - locks function fun to avoid deletion
clc - clears screen
clf - clears figureTermination Commands
ctrl + c - stop execution being run
quit - quits MATLAB
exit - same as quit
Help Commands help - list the help topic
help topic - list help on topic stated
lookfor string - list comment lines with string from all .m files
help matfun - list matrix functions of numerical linear algebra
7/30/2019 MATLAB-Introduction to Applications
20/62
Character Set
Characters classified as :
Alphabets (case sensitive): A - Z, a - z
Numerals: 0 to 9
Special Characters: [ ] ( ) { } = ' . ... , ; : % !
@
White space characters: tab, blank, new line
7/30/2019 MATLAB-Introduction to Applications
21/62
Data Types
Data types are in the form of array. Minimun single
element to an n-dimensional array
The char data type: hello , is a character array.Charstring is 1-by-n array
Numeric data type: int8, uint8, int16,uint16 include
signed and unsigned integer arrays.
7/30/2019 MATLAB-Introduction to Applications
22/62
Data Types
Cell array: Used for storing dissimilar kinds of
data
A=[ 1 2 7 8];B=[2 3 6; 6 3 8; 2 8 4];
C=zeros(2,3,3)
D_cell={A B C}; It is a cell array of three cells
7/30/2019 MATLAB-Introduction to Applications
23/62
Data Types
Structure data type: data is stored in named
fields rather than cells
abc.name = Prasanta Sarkar
abc.age = 52
abc.sex = male
7/30/2019 MATLAB-Introduction to Applications
24/62
Special Variables & Constants
ans Default variable name for results
pi Value of
eps Smallest incremental number
inf Infinity
NaN Not a number (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 nargin no. of input arguments in a function
nargout no. of output arguments in a function
7/30/2019 MATLAB-Introduction to Applications
25/62
Display formats
MATLAB supports these formats for outputting numericalresults.
format long 16 digits
format short e 5 digits plus exponent
format long e 16 digits plus exponent
format hex hexadecimal
format bank two decimal digits
format + positive, negative or zero format rat rational number (513/6)
format short default display
7/30/2019 MATLAB-Introduction to Applications
26/62
MATLAB AS A
CALCULATOR
Command window
>> 39*4.4+5
ans =
176.6000
Command window
The MATLAB command
The result.
7/30/2019 MATLAB-Introduction to Applications
27/62
MATLAB AS A
CALCULATOR
39*4.4+5
ans =
176.6000
this is the MATLAB prompt.It indicates that MATLAB is
ready to accept yourcommand
The MATLAB command
This is the result.
7/30/2019 MATLAB-Introduction to Applications
28/62
MATLAB Assignment
A=2.3
A =
2.3000
this is the MATLAB prompt.It indicates that MATLAB is
ready to accept your
command
The MATLAB command
This is the result of theMATLAB statement
7/30/2019 MATLAB-Introduction to Applications
29/62
Scalar Assignment
A=[2.3]
A =2.3000
The square brackets [ ] are used to
define matrices. We can use them
for scalars too.
this creates a variable A and set
its value to 2.3
A=2.3
A =
2.3000
7/30/2019 MATLAB-Introduction to Applications
30/62
Row vector
X =
2 3 7
X=[2,3 7 ] Space or comma are used toseparate elements in the same
row
The square braces areused to define a matrix
7/30/2019 MATLAB-Introduction to Applications
31/62
MATLAB Statements
MATLAB Statement Remarks
C=5.66 C is a scalar
C=[5.66] An alternative way
X=[3.5 6.3, 33]
X is a 1X3 matrix with elements 3.5 ,
6.3 and 33. Commas or space areused to separate the elements in a row
Y=[1
4 ]
Y is a 2X1 matrix whose elements are 1
and 4.
Y = [ 1 ; 4] Semicolon are used to indicate the endof the row.
A=1:5 Equivalent to A=[1 2 3 4 5]
7/30/2019 MATLAB-Introduction to Applications
32/62
MATLAB Statements
10
01V
MATLABStatement
Remarks
V=[ 2 3 5
3 3 8]
C=[1:3:11] C=[1 4 7 10]
Z=4\8 Z=2
Y=eye(2)
W = zeros(2,4)
833
532V
000
000V
7/30/2019 MATLAB-Introduction to Applications
33/62
Polynomialsroots(p) Find the roots of a polynomial
whose coefficients are given in p
roots([1 4 2.1]) Find the roots of x2+4x+2.1=0
polyval(p,v) Evaluate the polynomial whose
coefficients are given in p at x=v
M t i
7/30/2019 MATLAB-Introduction to Applications
34/62
Matrices
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 =
1
2
5
1
7/30/2019 MATLAB-Introduction to Applications
35/62
Matrices
x(i,j) subscription
whole row
whole column
y=x(2,3)
y =
4
y=x(3,:)
y =
3 2 -1
y=x(:,2)
y =
2
1
2
7/30/2019 MATLAB-Introduction to Applications
36/62
Operators (arithmetic)
+ addition
- subtraction
* multiplication
/ division
^ power
complex
conjugate
transpose
.* element-by-element mult
./ element-by-element div
.^ element-by-element power
. transpose
7/30/2019 MATLAB-Introduction to Applications
37/62
Logical Operators
> Greater than
>= Greater than or equal
< Less than
7/30/2019 MATLAB-Introduction to Applications
38/62
Logical Operators
& AND
| OR
~ NOT
if (X>6) |(x
7/30/2019 MATLAB-Introduction to Applications
39/62
Generating Vectors from
functions zeros(M,N) MxN matrix
of zeros
ones(M,N) MxN matrix
of ones
rand(M,N) MxN matrix
of uniformly distributedrandom numbers
on (0,1)
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
7/30/2019 MATLAB-Introduction to Applications
40/62
Operators
[ ] concatenation
( ) subscription
x = [ zeros(1,3) ones(1,2) ]
x =
0 0 0 1 1
x = [ 1 3 5 7 9]x =
1 3 5 7 9
y = x(2)
y =
3
y = x(2:4)
y =
3 5 7
7/30/2019 MATLAB-Introduction to Applications
41/62
Matlab Graphics
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of theSine Function')
7/30/2019 MATLAB-Introduction to Applications
42/62
Multiple Graphs
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
plot(t,y1,t,y2)grid on
7/30/2019 MATLAB-Introduction to Applications
43/62
Multiple Plots
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
subplot(2,2,1)plot(t,y1)
subplot(2,2,2)
plot(t,y2)
7/30/2019 MATLAB-Introduction to Applications
44/62
Graph Functions (summary)
plot linear plot
stem discrete plot
grid add grid lines
xlabel add X-axis label
ylabel add Y-axis label
title add graph title
subplot divide figure window figure create new figure window
pause wait for user response
7/30/2019 MATLAB-Introduction to Applications
45/62
Math Functions
Elementary functions (sin, cos, sqrt, abs, exp, log10, round)
type help elfun
Advanced functions (bessel, beta, gamma, erf)
type help specfun
type help elmat
7/30/2019 MATLAB-Introduction to Applications
46/62
Functions Files
function f=myfunction(x,y)
f=x+y;
save it in myfunction.m
call it with y=myfunction(x,y)
7/30/2019 MATLAB-Introduction to Applications
47/62
Function Files
A function file (called an M-file) is a text (ASCII) filethat contains a MATLAB function and, optionally,comments
The file is saved with the function name having usualMATLAB script file extension .m
A MATLAB function may be called from thecommand line or from any other M-file
When the function is called, it is executed, and controlis returned to the MATLAB workspace
Any values to be returned must be specified in thefunction syntax
function [out1, out2, ...] = myfun_name (in1, in2, ...)
7/30/2019 MATLAB-Introduction to Applications
48/62
Example of a Function File
Create an M-file and save as swap.m
function [ a , b ] = swap ( a , b )
% These are comments
% the function swap receives two values a, b in the ( )
% swaps them, and returns the result in a, b in the [ ]
% the file is saved as swap.m
temp=a;
a=b;
b=temp;
7/30/2019 MATLAB-Introduction to Applications
49/62
Example of a Function File
To use the function swap a MATLAB program could
assign values to two variables and then call the
function to swap them.>> x=5;>> y=6;
>> [ x, y ] = swap(x, y)
x =
6y =
5
7/30/2019 MATLAB-Introduction to Applications
50/62
Flow Controlif A > B
'greater'
elseif A < B
'less'
else
'equal'
end
for x = 1:10
r(x) = x;
end
if statement
switch statement
for loops
while loops
continue statement
break statement
7/30/2019 MATLAB-Introduction to Applications
51/62
7/30/2019 MATLAB-Introduction to Applications
52/62
if/elseif /else Statement
>> A = 2; B = 3;
>> if A > B
'A is bigger'
elseif A < B
'B is bigger'
elseif A == B
'A equals B'
else
error ('Something odd is happening')
end
ans =
B is bigger
7/30/2019 MATLAB-Introduction to Applications
53/62
for loops
General form:for index=initial:
increment: limit
statements
end
s=0
for i=1:3:11
s=s+i
end
7/30/2019 MATLAB-Introduction to Applications
54/62
for Loop
>> for i = 2:5
for j = 3:6
a(i, j) = (i + j)^2
end
end
>> a
a =
0 0 0 0 0 0
0 0 25 36 49 64
0 0 36 49 64 81
0 0 49 64 81 100
0 0 64 81 100 121
7/30/2019 MATLAB-Introduction to Applications
55/62
switch Statement>> n = 8;
>> switch (rem(n,3))
case 0
m = 'no remainder'
case 1m = the remainder is one'
case 2
m = the remainder is two'
otherwiseerror ('not possible')
end
m =
the remainder is two
7/30/2019 MATLAB-Introduction to Applications
56/62
while Loop
>> b = 4; a = 2.1; count =0;
>> while b - a > 0.01
a = a + 0.001;
count = count + 1;
end
>> countcount =
1891
7/30/2019 MATLAB-Introduction to Applications
57/62
Miscellaneous
Loading data from a file
load myfile.dat
Suppressing Output
x = [1 2 5 1];
Random Numbers
7/30/2019 MATLAB-Introduction to Applications
58/62
Random Numbers
x=rand(100,1);
stem(x);
hist(x,100)
7/30/2019 MATLAB-Introduction to Applications
59/62
Coin Tosses
Simulate the outcomes of 1000 biased coin
tosses with p[Head]=0.4
x=rand(1000,1);p=sum(x
7/30/2019 MATLAB-Introduction to Applications
60/62
Help
A good idea is use the help
help provides information about the availablefunctions and how to use them.
Tryhelp eig
help inv
help roots
7/30/2019 MATLAB-Introduction to Applications
61/62
Getting Help
Using the Help Browser (.html, .pdf)
View getstart.pdf, graphg.pdf, using_ml.pdf
Type help
help function, e.g. help plot
Running demos
type demos
type help demos
7/30/2019 MATLAB-Introduction to Applications
62/62
Thank You