0% found this document useful (0 votes)
4 views92 pages

Intro To Mat ANN

The document provides an introduction to MATLAB, highlighting its capabilities as a powerful tool for computation, programming, and visualization in engineering and science. It covers various aspects including MATLAB toolboxes, the working environment, basic interfaces, and fundamental operations with arrays and matrices. Additionally, it discusses variable management, string functions, and matrix operations, emphasizing the importance of vectorization for performance.

Uploaded by

ghashian135
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views92 pages

Intro To Mat ANN

The document provides an introduction to MATLAB, highlighting its capabilities as a powerful tool for computation, programming, and visualization in engineering and science. It covers various aspects including MATLAB toolboxes, the working environment, basic interfaces, and fundamental operations with arrays and matrices. Additionally, it discusses variable management, string functions, and matrix operations, emphasizing the importance of vectorization for performance.

Uploaded by

ghashian135
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 92

Introduction to Matlab

Imran Hassan
MATLAB
• “MATrix LABoratory”

• Powerful, extensible, highly integrated


computation, programming, visualization, and
simulation package

• Widely used in engineering, mathematics,


and science

Intro MATLAB
MATLAB Toolboxes
Math and Analysis Signal & Image Processing
Optimization Signal Processing
Requirements Management Interface Image Processing
Statistics Communications
Neural Network Frequency Domain System Identification
Symbolic/Extended Math Higher-Order Spectral Analysis
Partial Differential Equations System Identification
PLS Toolbox Wavelet
Mapping Filter Design
Spline
Control Design
Data Acquisition and Import Control System
Data Acquisition Fuzzy Logic
Instrument Control Robust Control
Excel Link μ-Analysis and Synthesis
Portable Graph Object Model Predictive Control

Intro MATLAB
MATLAB System
• Language: arrays and matrices, control flow, I/O, data
structures, user-defined functions and scripts
• Working Environment: editing, variable management,
importing and exporting data, debugging, profiling
• Graphics system: 2D and 3D data visualization, animation
and custom GUI development
• Mathematical Functions: basic (sum, sin,…) to advanced
(fft, inv, Bessel functions, …)

Intro MATLAB
Basic Interfaces
Main MATLAB Interface

Intro MATLAB
Some MATLAB Development Windows

• Command Window: where you enter commands


• Command History: running history of commands which is preserved
across MATLAB sessions
• Current directory: Default is $matlabroot/work
• Workspace: GUI for viewing, loading and saving MATLAB variables
• Array Editor: GUI for viewing and/or modifying contents of MATLAB
variables (openvar varname or double-click the array’s name in the
Workspace)
• Editor/Debugger: text editor, debugger; editor works with file types in
addition to .m (MATLAB “m-files”)

Intro MATLAB
MATLAB Editor Window

Intro MATLAB
MATLAB Help Window (Very
Powerful)

Intro MATLAB
Command-Line Help : List of MATLAB
Topics
>> help
HELP topics:

matlab\general - General purpose commands.


matlab\ops - Operators and special characters.
matlab\lang - Programming language constructs.
matlab\elmat - Elementary matrices and matrix manipulation.
matlab\elfun - Elementary math functions.
matlab\specfun - Specialized math functions.
matlab\matfun - Matrix functions - numerical linear algebra.
matlab\datafun - Data analysis and Fourier transforms.
matlab\polyfun - Interpolation and polynomials.
matlab\funfun - Function functions and ODE solvers.
matlab\sparfun - Sparse matrices.
matlab\scribe - Annotation and Plot Editing.
matlab\graph2d - Two dimensional graphs.
matlab\graph3d - Three dimensional graphs.
matlab\specgraph - Specialized graphs.
matlab\graphics - Handle Graphics.
…etc...

Intro MATLAB
Command-Line Help : List of Topic
Functions
>> help matfun
Matrix functions - numerical linear algebra.

Matrix analysis.
norm - Matrix or vector norm.
normest - Estimate the matrix 2-norm.
rank - Matrix rank.
det - Determinant.
trace - Sum of diagonal elements.
null - Null space.
orth - Orthogonalization.
rref - Reduced row echelon form.
subspace - Angle between two subspaces.

Intro MATLAB
Command-Line Help : Function Help
>> help det
DET Determinant.
DET(X) is the determinant of the square matrix X.

Use COND instead of DET to test for matrix


singularity.

See also cond.

Overloaded functions or methods (ones with the


same
name in other directories)
help laurmat/det.m

Reference page in Help browser


doc det

Intro MATLAB
Keyword Search of Help Entries
>> lookfor who
newton.m: % inputs: 'x' is the number whose
square root we seek
testNewton.m: % inputs: 'x' is the number
whose square root we seek
WHO List current variables.
WHOS List current variables, long form.
TIMESTWO S-function whose output is two times
its input.

>> whos
Name Size Bytes Class Attributes
ans 1x1 8 double
fid 1x1 8 double
i 1x1 8 double

Intro MATLAB
Variables (Arrays) and
Operators
Variable Basics
>> 16 + 24 no
nodeclarations
declarationsneeded
needed
ans =
40

>> product = 16 * 23.24 mixed


mixeddata
data
product = types
types
371.84
semi-colon
semi-colonsuppresses
suppressesoutput
output
>> product = 16 *555.24; of
ofthe
thecalculation’s
calculation’sresult
result
>> product
product =
8883.8

Intro MATLAB
Variable Basics
>> clear
clearremoves
clear removesall
allvariables;
variables;
>> product = 2 * 3^3;
>> comp_sum = (2 + 3i) + (2 clear xx yyremoves
- 3i); clear removesonly
onlyxxand
and
>> show_i = i^2; yy
>> save three_things complex
complexnumbers
numbers(i(ior j)require
orj) require
>> clear no
nospecial
specialhandling
handling
>> load three_things
>> who
Your variables are: save/loadare
save/load areused
usedto
to
comp_sum product show_i retain/restore
retain/restoreworkspace
workspace
>> product variables
variables
product =
54
>> show_i use hometo
usehome toclear
clearscreen
screenand
andput
put
show_i = cursor
cursoratatthe
thetop
topofofthe
thescreen
screen
-1

Intro MATLAB
MATLAB Data

The basic data type used in MATLAB is the double precision
array

• No declarations needed: MATLAB automatically allocates required


memory

• Resize arrays dynamically

• To reuse a variable name, simply use it in the left hand side


of an assignment statement

Intro MATLAB
Variables Revisited
• Variable names are case sensitive and over-written when re-used

• Basic variable class: Auto-Indexed Array


– Allows use of entire arrays (scalar, 1-D, 2-D,
etc…) as operands
– Vectorization: Always use array operands to
get best performance (see next slide)

• Terminology: “scalar” (1 x 1 array), “vector” (1 x N array), “matrix” (M x


N array)

• Special variables/functions: ans, pi, eps, inf, NaN, i,


nargin, nargout, varargin, varargout, ...

• Commands who (terse output) and whos (verbose output) show


variables in Workspace

Intro MATLAB
Vectorization
Example*
>> type slow.m >> type fast.m
tic; tic;
x=0.1; x=0.1:0.001:200;
for k=1:199901 y=besselj(3,x) + log(x);
y(k)=besselj(3,x) + toc;
log(x); >> fast
x=x+0.001; Elapsed time is 0.551970
end seconds.
toc;
>> slow Roughly 31 times faster
Elapsed time is 17.092999
seconds. without use of for loop
*times measured on this laptop

Intro MATLAB
Multidimensional Arrays
>> r = randn(2,3,4) % create a 3 dimensional array filled
with
normally distributed random numbers
r(:,:,1) =
“%”
“%”sign
signprecedes
precedescomments,
comments,
-0.6918 1.2540 -1.4410 MATLAB ignores the rest of the line
MATLAB ignores the rest of the line
0.8580 -1.5937 0.5711
r(:,:,2) =
randn(2,3,4): 3 dimensions, filled
-0.3999 0.8156 1.2902 randn(2,3,4): 3 dimensions, filled
with
withnormally
normallydistributed
distributedrandom
random
0.6900 0.7119 0.6686 numbers
numbers
r(:,:,3) =
1.1908 -0.0198 -1.6041
-1.2025 -0.1567 0.2573
r(:,:,4) =
-1.0565 -0.8051 0.2193
1.4151 0.5287 -0.9219

Intro MATLAB
Character Strings

>> hi = ' hello';


>> class = 'MATLAB';
>> hi
hi =
hello
>> class
class =
MATLAB
>> greetings = [hi class] concatenation
concatenationwith
withblank
blankor
orwith
with“,”
“,”
greetings =
helloMATLAB
>> vgreetings = [hi;class] semi-colon:
semi-colon:join
joinvertically
vertically
vgreetings =
hello
MATLAB

Intro MATLAB
String Functions
yo =
Hello
Class

>> ischar(yo)
ans = returns
returns11ififargument
argumentisisaacharacter
character
1 array
arrayand
and00otherwise
otherwise

>> strcmp(yo,yo)
ans =
1
returns
returns11ififstring
stringarguments
argumentsare
arethe
the
same
sameand
and00otherwise; strcmpiignores
otherwise;strcmpi ignores
case
case

Intro MATLAB
Set Functions
Arrays are ordered sets:

>> a = [1 2 3 4 5]
a =
1 2 3 4 5
>> b = [3 4 5 6 7]
b =
3 4 5 6 7
returns
returnstrue
true(1)
(1)ififarrays
arraysare
arethe
thesame
same
>> isequal(a,b) size
sizeand
andhave
havethe
thesame
samevalues
values
ans =
0
returns
returns11where
whereaaisisininbb
>> ismember(a,b) and
and00otherwise
otherwise
ans =
0 0 1 1 1

Intro MATLAB
Matrix Operations
>> durer = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]

durer = MATLAB
MATLABalso
alsohas
has
16 3 2 13 magic(N)
magic(N) (N (N >>
2)
2)
5 10 11 8
function
function
9 6 7 12
4 15 14 1

>> % durer's matrix is "magic" in that all rows,


columns,
>> % and main diagonals sum to the same number
>> column_sum = sum(durer) % MATLAB operates column-
wise

column_sum =
34 34 34 34

Intro MATLAB
Transpose Operator
>> % to get the row sums, we'll use the transpose
operator
>> % (an apostrophe)

>> durer'
ans =
16 5 9 4
3 10 6 15
2 11 7 14
13 8 12 1

>> row_sums = sum(durer')'


row_sums =
34
34
34
34

Intro MATLAB
Diagonal Elements
>> durer
durer =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1

>> diag(durer) % diag plucks out the diagonal elements


ans =
16
10
7
1

>> sum(diag(durer))
ans =
34

Intro MATLAB
The Other Diagonal…
>> durer
durer =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1

>> fliplr(durer) % “flip left-right”


ans =
13 2 3 16
8 11 10 5
12 7 6 9
1 14 15 4
>> sum(diag(fliplr(durer)))
ans =
34

Intro MATLAB
Matrix Subscripting
>> durer
durer =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1

>> diag_sum = durer(1,1) + durer(2,2) + durer(3,3)


diag_sum =
33
>> durer(4,4) = pi
durer =
16.0000 3.0000 2.0000 13.0000
5.0000 10.0000 11.0000 8.0000
9.0000 6.0000 7.0000 12.0000
4.0000 15.0000 14.0000 3.1416

>> durer(4,4) = 1

Intro MATLAB
Colon Operator (Vector
Creation)
>> 1:5 % use the colon operator to create row vectors
ans =
1 2 3 4 5

>> 1:0.9:6 % you can vary the increment (0.9 in this


case)
ans =
1.0000 1.9000 2.8000 3.7000 4.6000
5.5000

The last element is always less than or equal


to the upper limit

Intro MATLAB
Colon Operator (Indexing)
>> sum(durer(1:3,4)) % sums first three
% elements of column 4
ans =
33

>> sum(durer(:,end)) % a lone colon is ALL


% elements, end is
% the last element
ans =
34

Intro MATLAB
The “Dot Operator”
• By default and whenever possible MATLAB will
perform true matrix operations (+ - *). The
operands in every arithmetic expression are
considered to be matrices.
• If, on the other hand, the user wants the scalar
version of an operation a “dot” must be put in
front of the operator, e.g., .*. Matrices can still
be the operands but the mathematical
calculations will be performed element-by-
element.

Intro MATLAB
Dot Operator Example
>> A = [1 5 6; 11 9 8; 2 34 78]
A =
1 5 6
11 9 8
2 34 78
>> B = [16 4 23; 8 123 86; 67 259 5]
B =
16 4 23
8 123 86
67 259 5

Intro MATLAB
Dot Operator Example (cont.)
>> C = A * B % “normal” matrix multiply
C =
458 2173 483
784 3223 1067
5530 24392 3360

>> CDOT = A .* B % element-by-element


CDOT =
16 20 138
88 1107 688
134 8806 390

Intro MATLAB
Two Division Operators
• Right divide (familiar version) a/b
– What happens: a is divided by b
– Right operand “goes into” left operand
• Left divide a\b
– What happens: b is divided by a
– Left operand “goes into” right operand
– Behaviour depends on operands (scalar vs. matrix)

• Both operators work with matrices (of course). More


later on what is actually calculated …
• Comparison of the use of / and \ on next slide

Intro MATLAB
Using the Division Operators
>> x = 53.0;
>> y = 22.5;

>> x/y

ans = 2.3556
For matrix operands, A\B is the solution
>> x\y
to
ans = 0.4245 Ax = B obtained by Gaussian
elimination.
>> (x/y)^(-1)
Read “Arithmetic Operators + - * / \ ^ ’
ans = 0.4245 ”
in “MATLAB Function Reference”:
Help  Search for: division
Intro MATLAB
Easy 2-D Graphics
>> x = [0: pi/100: pi]; % [start: increment: end]
>> y = sin(x);
>> plot(x,y), title('Simple Plot')

Intro MATLAB
Adding Another Curve
>> z = cos(x);
>> plot(x,y,'g.',x,z,'b-.'),title('More complicated')

Line
Linecolor,
color,style,
style,marker
markertype,
type,
all
allwithin
withinsingle
singlequotes;
quotes;type
type
>>
>> doc
doc LineSpec
LineSpec
for
forall
allavailable
availableline
lineproperties
properties

Intro MATLAB
Programming
Outline

• MATLAB m-file Editor


– To start: click icon or enter edit command in
Command Window, e.g., >> edit test.m
• Scripts and Functions
• Decision Making/Looping
– if/else
– switch
– for and while
• Running Operating System Commands

Intro MATLAB
m-file Editor Window

You
Youcancansave
saveand
andrun
runthe
the
file/function/script
file/function/scriptininone
one
step by clicking here
step by clicking here

Tip:
Tip:semi-colons
semi-colonssuppress
suppressprinting,
printing,commas
commas(and(and
semi-colons)
semi-colons) allow multiple commands on oneline,
allow multiple commands on one line,
and 3 dots (…) allow continuation of lines without
and 3 dots (…) allow continuation of lines without
execution
execution

Intro MATLAB
Scripts and Functions

• Scripts do not accept input arguments, nor do they


produce output arguments. Scripts are simply
MATLAB commands written into a file. They operate
on the existing workspace.
• Functions accept input arguments and produce
output variables. All internal variables are local to the
function and commands operate on the function
workspace.
• A file containing a script or function is called an m-file
• If duplicate functions (names) exist, the first in the
search path (from path command) is executed.

Intro MATLAB
Functions – First Example
function [a b c] = myfun(x, y) Write
Writethese
thesetwo
twolines
linesto
toaafile
file
b = x * y; a = 100; c = x.^2; myfun.m and
myfun.m andsave
saveititon
onMATLAB’s
MATLAB’s
path
path
>> myfun(2,3) % called with zero outputs
ans =
100
>> u = myfun(2,3) % called with one output
u =
100
>> [u v w] = myfun(2,3) % called with all outputs
u =
100
v = Any
Anyreturn
returnvalue
valuewhich
whichisisnot
notstored
stored
6 in
inan
anoutput
outputvariable
variableis
issimply
simply
w = discarded
discarded
4

Intro MATLAB
Function: Header/Help Comments
function angles = ortho(a,b,c)
%ortho function input: Three vectors each with 3 elements
% The output is a 3-element array containing the
% angles between each pair of input vectors. The
% output elements are respectively:
% angle between a and b
H1 (help 1) line displayed
% angle between b and c
% angle between a and c when using lookfor
% Typical use or ortho is to determine if a,b,c form an
% orthogonal basis set that spans 3-D space.

All initial comment lines are displayed when help is used on a function
NOTE: This function should be saved in a file named
ortho.m

Intro MATLAB
Function: Body
anorm = norm(a); % Local Variables
bnorm = norm(b); % Calculate vector lengths
cnorm = norm(c);
ab = dot(a,b); % Calculate Dot Products
bc = dot(b,c);
ac = dot(a,c);
cosy_ab = ab/(anorm*bnorm); % Calculate cosine of
cosy_bc = bc/(bnorm*cnorm); % included angles
cosy_ac = ac/(anorm*cnorm);
angles(1) = convert2deg(acos(cosy_ab)); % Create output
angles(2) = convert2deg(acos(cosy_bc));
angles(3) = convert2deg(acos(cosy_ac));
return

Intro MATLAB
Using Your ortho Function
>> a = [1 2 3];
>> b = [4 5 6];
>> c = [7 8 9];
>> ortho(a,b,c)
ans =
12.9332 3.4470 16.3801
>> a = [22 0 0];
>> b = [0 5 0];
>> c = [0 0 13];
>> ortho(a,b,c)
ans =
90 90 90

Intro MATLAB
Getting ortho Function Help
>> help ortho
ortho function input: Three vectors each with 3 elements
The output is a 3-element array containing the angles
between each pair of input vectors. The output
elements are respectively:
angle between a and b
angle between b and c
angle between a and c
Typical use or ortho is to determine if a,b,c form an
orthogonal basis set that spans 3-D space.

>> help sin


SIN Sine.
SIN(X) is the sine of the elements of X.

See also asin, sind.

Intro MATLAB
Function Syntax Summary
• If the m-file name and function name differ, the file
name takes precedence

• Function names must begin with a letter

• First line must contain function followed by the most


general calling syntax

• Statements after initial contiguous comments (help


lines) are the body of the function

• Terminates on the last line or a return statement

Intro MATLAB
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

Intro MATLAB
switch Statement
>> n = 8
n =
8
>> switch(rem(n,3))
case 0
m = 'no remainder'
case 1
m = ‘the remainder is one'
case 2
m = ‘the remainder is two'
otherwise
error('not possible')
end
m =
the remainder is two

Intro MATLAB
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

Intro MATLAB
while Loop

>> b = 4; a = 2.1; count = 0;


>> while b - a > 0.01
a = a + 0.001;
count = count + 1;
end
>> count
count =
1891

Intro MATLAB
Changing the Search Path
• The addpath command adds directories to the MATLAB
search path. The specified directories are added to the
beginning of the search path.
>> path >> addpath('c:\');
>> matlabpath
MATLABPATH
MATLABPATH
E:\MATLAB\R2006b\work c:\
E:\MATLAB\R2006b\work\f_funcs E:\MATLAB\R2006b\work
E:\MATLAB\R2006b\work\na_funcs E:\MATLAB\R2006b\work\f_funcs
E:\MATLAB\R2006b\work\na_scripts E:\MATLAB\R2006b\work\na_funcs
E:\MATLAB\R2006b\toolbox\matlab\ E:\MATLAB\R2006b\work\na_scripts
general E:\MATLAB\R2006b\toolbox\matlab\general
E:\MATLAB\R2006b\toolbox\matlab\ops E:\MATLAB\R2006b\toolbox\matlab\ops

• rmpath is used to remove paths from the search path

Intro MATLAB
Data I/O
Loading and Saving Workspace
Variables
• MATLAB can load and save data in .MAT format

• .MAT files are binary files that can be transferred across


platforms; as much accuracy as possible is preserved.

• Load: load filename OR A = load(‘filename’)


loads all the variables in the specified file (the default name is
MATLAB.MAT)

• Save: save filename variables


saves the specified variables (all variables by default) in the
specified file (the default name is MATLAB.MAT)

Intro MATLAB
Import Wizard
Import ASCII and binary files using the Import Wizard. Type
uiimport at the Command line or choose Import Data from the
File menu.

Intro MATLAB
Low-Level File I/O Functions
• File Opening and Closing
– fclose: Close one or more open files
– fopen: Open a file or obtain information about open files
• Unformatted I/O
– fread: Read binary data from file
– fwrite: Write binary data to a file
• Formatted I/O
– fgetl: Return the next line of a file as a string
without line terminator(s)
– fgets: Return the next line of a file as a string with line
terminator(s)
– fprintf: Write formatted data to file
– fscanf: Read formatted data from file

Intro MATLAB
Low-Level File I/O (cont.)
• File Positioning
– feof: Test for end-of-file
– ferror: Query MATLAB about errors in file input
or output
– frewind: Rewind an open file
– fseek: Set file position indicator
– ftell: Get file position indicator

Intro MATLAB
File Open (fopen)/Close (fclose)
• fid = fopen(‘filename’, ‘permission’);

Permission
File Name of requested:
identifier file ‘r’, ’r+’
number ‘w’, ’w+’
‘a’, ’a+’

• status = fclose(fid);

0, if successful File identifier number


-1, otherwise or ‘all’ for all files

Intro MATLAB
Formatted I/O
• fscanf: [A, count] = fscanf(fid,format,size);

Number File Format Amount of


Data successfully identifier specifier data to read:
array read number n, [n, m], Inf
• fprintf: count = fprintf(fid, format, A,...);

Number File Format Data


successfully identifier specifier array(s) to
read number write

fscanf and fprintf are similar to C version but vectorized

Intro MATLAB
Structures
• Multidimensional MATLAB arrays
• Access elements using textual field designators
• Create structures by using periods (.):
>> class.name = ‘MATLAB’;
>> class.day1 = ‘2/27/07’;
>> class.day2 = ‘2/28/07’;
>> class
class =
name: ‘MATLAB’
day1: ‘2/27/07’
day2: ‘2/28/07’

Intro MATLAB
Manipulating Structures
• Structures are arrays (no surprise)
• Fields can be added one at a time:

>> class(2).name = ‘MPI’;


>> class(2).day1 = ‘TBA’;
>> class(2).day2 = ‘TBA’;

• Can also use a single statement:

>> class(2) = struct(‘name’,‘MPI’,...

‘day1’,‘TBA’,‘day2’,‘TBA’)
Intro MATLAB
Manipulating Structures (cont.)
• Consider the simple structure

>> exam.name = ‘Jim Kirk’;


>> exam.score = 79;
>> exam(2).name = ‘Janice Lester’;
>> exam(2).score = 89;
>> [exam.score]
ans =
square
squarebrackets
bracketsproduce
produce
79 89 a numeric row vector
a numeric row vector

Intro MATLAB
Basic Data Analysis
Basic Data Analysis

• Basic, and more advanced, statistical


analysis is easily accomplished in MATLAB.

• Remember that the MATLAB default is to


assume vectors are columnar.

• Each column is a variable, and each row is an


observation.

Intro MATLAB
Vibration Sensors Data

Each
Eachcolumn
columnisis
the
theraw
rawrpm
rpm
sensor
sensor datafrom
data from
aadifferent
different sensor
sensor
used
usedininanan
instrumented
instrumented
engine
enginetest.
test.The
The
rows represent
rows represent
the
thetimes
times
readings
readingswere
were
made.
made.

Intro MATLAB
Plotting the Data
>> plot(rpm_raw)
>> xlabel('sample number - during time slice');
>> ylabel('Unfiltered RPM Data');
>> title(‘3 sequences of samples from RPM sensor’)

Note
Notethat
thatininthis
thiscase
case
the
theplot
plotcommand
command
generates
generatesone onetime-
time-
series
seriesfor
foreach
eachcolumn
column
ofofthe
thedata
datamatrix
matrix

Intro MATLAB
Average of the Data:
1
Applying >> mean(rpm_raw)
Applyingthe meanfunction
themean function
to
tothe
thedata
datamatrix
matrixyields
yields
the
themean
meanofofeach
eachcolumn
column ans =
1081.4 1082.8
1002.7
2
But
Butyou
youcan caneasily
easilycompute
compute
the
themean
meanof ofthe
theentire
entirematrix
matrix >> mean(mean(rpm_raw))
(applying
(applyingaafunction
functionto toeither
either
aasingle
singlerowrowororaasingle
single
column results in the function ans =
column results in the function
applied 1055.6
appliedto tothe
thecolumn,
column,or orthe
the
row,
row,i.e.,
i.e.,ininboth
bothcases,
cases,thethe
application
applicationis isto
tothe
thevector).
vector).

Intro MATLAB
The mean Function
>> help mean
MEAN Average or mean value.
For vectors, MEAN(X) is the mean value of the elements in X. For
matrices, MEAN(X) is a row vector containing the mean value of
each column. For N-D arrays, MEAN(X) is the mean value of the
elements along the first non-singleton dimension of X.

MEAN(X,DIM) takes the mean along the dimension DIM of X.


But
Butwe
wecan
canapply
applythe meanfunction
themean function
Example: If X = [0 1 2 along
3 4 5] alongany
anydimension
dimension

then mean(X,1) is [1.5 2.5 3.5] and mean(X,2) is [1


>> mean(rpm_raw, 2) 4]
ans = 3
1045.7
1064.7 So
Sowe
wecan
caneasily
easilyobtain
obtainthe
therow
row
1060.7 means
means
1055
1045

Intro MATLAB
max and its Index
1 MAX Largest component. 2
For vectors, MAX(X) is the largest
element in X. For matrices, MAX(X) >> max(rpm_raw)
is a row vector containing the ans =
maximum element from each column. 1115 1120 1043
For N-D arrays, MAX(X) operates
along the first non-singleton
dimension. >> max(max(rpm_raw))
ans =
[Y,I] = MAX(X) returns the indices 1120
of the maximum values in vector I.
If the values along the first non-
singleton dimension contain more >> [y,i] = max(rpm_raw)
than one maximal element, the index y =
of the first one is returned. 1115 1120 1043
We
Wecancancompute
computethethe i =
maxof
max ofthe
theentire
entirematrix,
matrix, 8 2 17
or
orof
ofany
anydimension
dimension max
maxalong
alongthe
thecolumns
columns

Intro MATLAB
Standard Deviation, Median,
Covariance
>> median(rpm_raw) % median along each column
ans =
1080 1083.5 1004
>> cov(rpm_raw) % covariance of the data
ans =
306.4 -34.76 32.192
-34.76 244.9 -165.21
32.192 -165.21 356.25
>> std(rpm_raw) % standard deviation along each
column
ans =
17.504 15.649 18.875
>> var(rpm_raw) % variance is the square of std
ans =
306.4 244.9 356.25

Intro MATLAB
Histogram (cont.)
>> hist(rpm_raw) %histogram of the data

Intro MATLAB
Sorting Data (cont.)
>> magic(4)
ans =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1

>> sort(magic(4)) 1
ans =
4 2 3 1
5 7 6 8
9 11 10 12
16 14 15 13

Intro MATLAB
Sorting Data (cont.)
>> magic(4) >> sort(magic(4),2)
ans = ans =
16 2 3 13 2 3 13 16
5 11 10 8 5 8 10 11
9 7 6 12 6 7 9 12
4 14 15 1 1 4 14 15
2
>> sort(magic(4),1)
ans =
4 2 3 1
5 7 6 8
9 11 10 12
16 14 15 13

Intro MATLAB
Basic XY Plot
>> x = [0:pi/100:pi];
>> y = sin(x);
>> plot(x,y), title('Simple Plot')

Intro MATLAB
Multiple Curve Plots
>> z = cos(x);
>> plot(x,y,'g.',x,z,'b-.'), title('More
Complicated')
Line
Linecolor,
color,style,
style,marker
marker
type,
type, all within singlequotes
all within single quotes

Intro MATLAB
Subplots
Used to display multiple plots in the same figure window,
subplot(m,n,i) subdivides the window into m-by-n subregions
(subplots) and makes the ith subplot active for the current plot
>> subplot(2,3,1)
>> plot(t, sin(t), 'r:square')
>> axis([-Inf,Inf,-Inf,Inf])
1 3

>> subplot(2,3,3)
2
>> plot(t, cos(t), 'g')
>> axis([-Inf,Inf,-1,1])

>> subplot(2,3,5)
>> plot(t, sin(t).*cos(t),
'b-.')
>> axis([-Inf,Inf,-Inf,Inf])
4 5 6

Intro MATLAB
ANN

Intro MATLAB
ANN Terminologies
– Neuron
• ANN is collection of artificial
neurons
• A neuron is the operational
unit of ANN which has
information processing
capability
• It has two units
– Linear Combiner
» Adds product of each Input and associated weights
– Activation function
» Maps the data collected in first unit into certain data range.
» Linear, piece wise or sigmoid
Intro MATLAB
Three Layers
Layers of ANN
Input; Hidden(s); Output
NN are made of neurons arranged in layers
Input Layer
Consisting of neurons that simple accept the input values
Output of a layer is input to the successive layer
Hidden layers
Layers between input and output are called hidden layers
Hidden Neurons
Neurons in the hidden layer are called hidden neurons.
Output Layer
Last layer which has the final output is called output layer

input

input
output
input

input Intro MATLAB


Face Pose Recognition
using ANN

Intro MATLAB
FR using ANN
• Three main parts
– Prepare the input and target vectors
– Train ANN
– Simulate to test

Intro MATLAB
• Preparing the data
– Reading Image:
• inp_f1=imread('Train\ap4c_left_neutral_closed.pgm');
• inp_f2=imread('Train\ap4c_right_neutral_closed.pgm');
• inp_f3=imread('Train\ap4c_straight_neutral_closed.pgm');

– Resizing

• imp_res_f1=imresize(inp_f1,0.5);
• imp_res_f2=imresize(inp_f2,0.5);
• imp_res_f3=imresize(inp_f3,0.5);

Intro MATLAB
• Preparing the data
– Converting Matrix into Vector

• f1=reshape(imp_res_f1,[],1);
• f2=reshape(imp_res_f2,[],1);
• f3=reshape(imp_res_f3,[],1);

– Creating input vector

• input=f1;
• input(:,2)=f2;
• input(:,3)=f3;

Intro MATLAB
• Preparing the data
– Creating a Target Vector

• tar=[0.95 0.95 0.05 0.05 0.05 0.05 0.95 0.95 0.05 0.05 0.05 0.05;
0.05 0.05 0.05 0.05 0.95 0.95 0.05 0.05 0.05 0.05 0.95 0.95;
0.05 0.05 0.95 0.95 0.05 0.05 0.05 0.05 0.95 0.95 0.05 0.05];

– Similarly same steps for Test data like Input vector

– Cast Input and Test data into double

• input=double(input);
• test=double(test);

Intro MATLAB
• Training ANN
net= newff(minmax(P),[12 6 3],{'logsig' 'logsig'
'purelin'},'traingd');
net.trainParam.show=50;
net.trainParam.epochs = 5000;
net.trainParam.goal=0.1
net.trainParam.lr = 0.05;
tic;
net = train(net,P,T);
toc;

save net

Intro MATLAB
• net = newff(PR,[S1 S2...SNl],{TF1 TF2...TFNl},BTF,BLF,PF)

• Description

• NET = NEWFF creates a new network with a dialog box.

• NEWFF(PR,[S1 S2...SNl],{TF1 TF2...TFNl},BTF,BLF,PF) takes,
• PR - Rx2 matrix of min and max values for R input elements.
• Si - Size of ith layer, for Nl layers.
• TFi - Transfer function of ith layer, default = 'tansig'.
• BTF - Backprop network training function, default = 'trainlm'.
• PF - Performance function, default = 'mse'.
• and returns an N layer feed-forward backprop network.

• The transfer functions TFi can be any differentiable transfer
• function such as TANSIG, LOGSIG, or PURELIN.

• The training function BTF can be any of the backprop training
• functions such as TRAINLM, TRAINBFG, TRAINRP, TRAINGD, etc.

Intro MATLAB
• traingd is a network training function that updates weight and
bias values according to gradient descent
• trainlm is a network training function that updates weight and
bias values according to Levenberg-Marquardt optimization.
• traingdm is a network training function that updates weight and
bias values according to gradient descent with momentum
• traingda is a network training function that updates weight and
bias values according to gradient descent with adaptive
learning rate
• traingdx is a network training function that updates weight and
bias values according to gradient descent momentum and an
adaptive learning rate.

Intro MATLAB
Intro MATLAB
Intro MATLAB
Intro MATLAB
• Testing and Using ANN for prediction and
classification

Y = sim(net,test);
display(Y);

Intro MATLAB
• Y=

• 0.5000 0.0500 0.0500 0.3500 0.0500 0.0500


• 0.5000 0.0500 0.0500 0.3500 0.0500 0.0500
• 0.0500 0.9500 0.9500 0.3500 0.9500 0.9500

Intro MATLAB

You might also like