Upload
devangmarvania
View
232
Download
1
Tags:
Embed Size (px)
DESCRIPTION
introduction of SVNIT
Citation preview
Department of Electronics Engineering
February 21, 2009
Introduction to
What is MATLAB History of MATLAB Why MATLAB MATLAB Applications How to start MATLAB M- File MATLAB toolboxs Keys to remember
MATrix LABoratory Calculator Interactive Programming language Scientific computation and visualization
tool Symbolic computing tool
4
4
Developed by Cleve Moler in Stanford in 70’s
To facilitate matrix and vector computations
Easier to program than Fortran Spread by word of mouth Mathworks, Inc established in 1984
http://www.mathworks.com/
A good choice for vision program development because: Easy to do very rapid prototyping Quick to learn, and good documentation A good library for various data processing
functions Excellent display capabilities Widely used for teaching and research in
universities and industry
Easy to Learn Vector formulation instead of scaler Programmable calculator Interpreter, Not Compiler - Easy to
debug Powerful graphics Add on toolboxes
It allows quick and easy coding in a very high-level language
Data structures require minimal attention; E.g., arrays need NOT be declared
before first use; An interactive interface allows rapid
experimentation and easy debugging
High-quality graphics and visualization facilities are available;
M-files are completed portable across a wide range of platforms;
Toolboxes can be added to extend the system, giving specialized signal processing facilities and a symbolic manipulation capability.
8
8
NASA Ames designs computer-aided joystick for spacecraft docking mechanism with MATLAB
GenCorp's Aerojet Division solves rocket fuel pressure control problem using MATLAB and Simulink.
Applied Biosystems develops a crucial DNA sequencing algorithm in MATLAB
Given Imaging developed M2A, a minimally invasive intestinal diagnostic tool, by MATLAB
B0
M(t)
y
x2D FFT-1
B1
RF
z
transmit/receive
Mag = (X2 + Y2)½
Pha = atan(Y/X)
X
Y
kx
kx
ky
ky R
I
K = R + i*I;C = ifft2(K); Z = fftshift(C);X = real(Z); Y = imag(Z);A = abs(Z); P = atan(Y ./ X);
Complex- valued k-space
MR Image formation Fourier imaging ...
MATLAB:
Matrix calculation Drawing graphs (2-D, 3-D) Symbolic/Statistic Computation Reading data from various sources
i.e. Excel file, .txt file Provide Graphical User Interface
11
Define Matrix
Matrix Operation >> determinant=det(A)
13
Polar plot t=0:.01:2*pi; polar(t,abs(sin(2*t).*cos(2*t))); Line plot
x=0:0.05:5; y=sin(x.^2); plot(x,y);
Stem plot: x = 0:0.1:4; y = sin(x.^2).*exp(-x);
stem(x,y)
14 14
Mesh plot:
z=peaks(25); mesh(z);
Surface plot: z=peaks(25); surf(z);
Contour plot:
z=peaks(25); contour(z,16); Spherical harmonic: spharm2
15
15
Differentiation:>> g=sin(x)*cos(y);
>> diff(g) % differentiate w.r.t. x
>> diff(g,y,3) % 3rd order partial derivative w.r.t. y
Integration:
>> g=(y^2-1)/(x^5+1); int(g,y) % integrate w.r.t. y
16
16
Scilab – MATLAB emulator http://www.scilab.org/ develop jointly by Chinese and French governments
Octave – MATLAB emulator http://www.octave.org/developed by Univ. of Wisconsin
Mathematica – symbolic computation http://www.wolfram.com/
Maple – symbolic computation incorporated in MATLAB http://www.maplesoft.com/
How to start MATLAB ?
17
To start MATLAB: Programs => MATLAB => MATLAB 7.4
Command Window:
where you input
MATLAB commands
Directory Window:
show the files in the directory
History Window:
record what you have
done
Matlab Window
Convenient to close all window except Command window
>> command prompt
Working in the command Window 1 Cursor must next to >> Once a command is typed, Enter key is pressed,
for Execution Several command in same line, Type comma
between the command, Enter key >> a=2,b=3 Use Up-Arrow key –command can be recall Too long command can be continued in the next
line by typing three periods …and press Enter Command continue total 4096 character
Working in the command Window 2
Semicolon(;): Typed at the end of command ,the output of
the command is not displayed(>> a=2,b=3;) Typing(%): before line-Comment Clc : clear the command window Execute the calculation according to
precedence (1.parentheses 2. Exponential, 3.Multiplication, Division 4.Addition & subtraction )
>> 27^(1/3)+32^0.2
+ addition− subtraction* multiplication^ power′ conjugate transpose\ left division[5\3=3/5]/ right divisionx = A\b the solution of A x = bx = b/A the solution of x A = b
Display format User can control Display format :
(Example:290/7)
Format short: Fixed point with 4 decimal Digit
Format long: Fixed point with 14 decimal Digit
Format short e: Scientific notation with 4 decimal Digit
Format long e: Scientific notation with 15 decimal Digit
Format short g: Best of 5 digits fixed or floting point
Format long g: Best of 15 digits fixed or floting point
Format bank: Two decimal digit>> format short>> 290/7
41.4286 41.428571428571431 4.1429e+00
4.142857142857143e+001
41.429
41.4285714285714
41.43
Display Formats
>> format compact >> a=5 a = 5 >> format loose >> a=5
a =
5
Help window Content, Index, Search, Demos
Help command (i.e. >>Help fft) Provide information about a specific function Show input and output argument
Doc command Provide information about specific function Includes example using MATLAB function
Lookfor command : Search for keyword
Illustrates the easy and powerful aspects of MATLAB
Consists of two parts Core MATLAB Toolboxes
Core MATLAB – desktop, matrices, graphics Toolboxes – financial, symbolic, Signal
Processong, Neural Network .....
26
26
To use Programs => MATLAB => MATLAB 7.4 Inside MATLAB window, look for
MATLAB prompt “>>” Type “demo” and hit “Enter” key On left panel, click “+” on MATLAB Click “+” on any one of the folders Click on any one of the examples
27
Elementary Math Built in Function
Large library of built in function Function is used, argument can be a
number, variable that has assigned a numerical value
>> squrt(81), exp(x), abs(-24), log(x), log10(x), factorial(x), sin(pi), cos(x), tan(x), cot(x), asin(x), sinh(x)
Rounding Function
Function round(x)
DescriptionRound to the nearest integer
Round(17/5)=3
Fix(x) Round towards zero Fix(13/5)=2
Ceil(x) Round towards infinity Ceil(11/5)=3
Floor(x)
Round towards -infinity Floor(-9/4)=-3
Rem(x,y)
Returns remainder Rem(13,5)=3
Sign(x) Returns 1 if x>0,-1if x<0, 0 if x=0
Sign(5)=1
Scalar Variable
Variable name= numeric value or expression Variable is name of memory location If the variable is assigned new value the
content of the memory location is replaced. Several assignment can be in the same line,
assignment must be separated with comma Once variable is assigned ,can be used
argument in function.
Example
>> x=15 x = 15 >> x=3*x-12 x = 33
>> a=12,b=4;c=(a-b)+40
a = 12 c = 48
Rules about Variable name
Variable names: Can be upto 63 character long Contain letters,digits and underscore
character Must begin with letter Matlab is case sensitive,different aa,aA,AA Avoid using the name of built in function
for a variable(avoid cos,sin,sqrt)
Predefined variable
ans Variable has the value of last expression ,not assigned specific variable
Pi Number Π
Eps The smallest difference bet two numbers
Inf Use for infinity
I Defined as
J Same as I
NaN
Not aNumber,0/0
1
Useful Commands for managing Varible
Command Outcome
clear Removes all variable from memory
Clear x,y,z Removes only x,y,z from memory
who Display a list of the variables currently in the memmory
whos Displays a list of variablecurrently in memmory,bytes,class
Numbers Integers (exact): 0, 1, 2, … Real numbers (approximate): 1., 2.1,
3e-8 Complex numbers: i = j = √ -1 Special values: pi Special “non-numbers”: Inf, NaN
35
35
Arithmetic Operators Unary: +, - Binary: +, -, *, /, \, ^ Strings: ‘Department of Electronics’
36
States: true (1, non-zero), false (0) Logical Operators
Unary: ~ Binary (relational): ==, ~=, >, >=, <,
<=, &, | “Short-circuit”: &&, ||
Only evaluates second operand if required Useful for conditional evaluation subject to e.g. <test> && <operation> only evaluates <operation> if the <test> is true.
37
Does not require any type declaration Automatically creates the variable and
allocate the appropriate amount of storage
Variable assignment operator : ‘=‘ A=1; a =2*pi;
At end of expression “ ; ” suppresses output.
38
38
+ addition− subtraction* multiplication^power′ conjugate transpose\ left division/ right divisionx = A\b the solution of A x = bx = b/A the solution of x A = b
>> -5/(3.45+2.75)^2ans =-0.1301
>> (2+6i)*(2-6i)ans =40
>> sin(pi/4)ans =0.7071
>> exp(acos(0.3))ans=3.547
>> b= a* cos(.76);
A = [1 2 0; 2 5 -1; 4 10 -1];semicolon starts new row
B = [3,4,5] ;create row vector: “,” to ;separate elements
C = [A;B] ;insert new row in matrixD = [A,B’] ;insert new column in matrixE = eye(5) ;create 5 x 5 identity matrixF = ones(2,3) ;create 2 x 3 matrix of ones
41
B = A’ ;transpose AC = A + 3*BD = A*BD = A.*B ;element by element
multiplicationE = A^2 ;multiply A by itselfE = A.^2 ;raise each element of A to
2ndpowerX = inv(A) ;form inverse of matrix
42
Matlab Command Output
[1,2,3].*[5,6,7] [5,12,21][10:-2:0]. ^ 2 [100,64,36,16,4,0]2. ^ [1:6] [2,4,8,16,32,64][2,4,6]./ 2 [1,2,3][2,4,6] . \ 2 [1.000 0.5000
0.3333]
The Matlab command help elfun gives a list of elementary math functions
Trigonometric: sin, sinh, asin, asinh, cos,cosh, acos, acosh, tan, tanh, atan,atan2, atanh, sec, sech, asech, csc,csch, acsc, acsch, cot, coth, acot, acoth
Expotential: exp, log, log10, log2, pow2,sqrt, nextpow2
Complex: abs, angle, complex, conj, imag,real, unwrap, isreal, cplxpair
Rounding and remainder: fix, floor, ceil,round, rem, sign
Entering MATLAB Command is not practical.
Solution : M-File
Script FunctionCollections of commands use define functionExecuted in sequence when called Has input -output
Saved with extension “.m”
File – New M file
x = linspace(0,2*pi,200);
Y1= sin(x);
Y2 = cos(x);
Plot((x,Y1,x,Y2)
Save as filename.m
To execute the command,
Debug Run
Accept input argumet and generate output
dependent_variables = function_name(independent_variables)
FunctionInput Output
y = x^2-1;
function y=react_C(c,f) %react_C calculates the reactance of a capacitor. %The inputs are: capacitor value and frequency in hz
%The output is 1/(wC) and angular frequency in rad/s
y(1)=2*pi*f; w=y(1); y(2)=1/(w*c); File must be saved to a known path with filename the same as the function name and with an extension ‘.m’ (i.e react_c.m)
Call function by its name and arguments
Communications Toolbox Control System Toolbox Database Toolbox Model-Based Calibration Toolbox Neural Network Toolbox Optimization Toolbox Partial Differential Equation (PDE) Toolbox Signal Processing Toolbox Statistics Toolbox Symbolic Math Toolbox System Identification Toolbox Wavelet Toolbox
; (Semicolon) Suppress the output of results to the screen
Up-arrow scroll through previously typed commands
Esc Clear command line
Ctrl+C Quit current operation and return control to the command line
Clear all Clear all variables
who This shows all active variables. Try the command whos
save filename This creates a file filename.mat which contains allVariables
save filename x y z
This creates a file filename.mat which containsvariables x y z
Thank You
det(A) determinant
rank(A)
inv(A) inverse
trace(A)
eig(A) eigenvalues
52
Use round brackets and (row, column)
notation
Let a = [1 2 3; 4 5 6; 7 8 9]
Accessing: a(2, 1) 4
Assigning : a(2, 1) = 0
53
Ranges of numbers: 1:10 [1 2 3 4 5 6 7 8 9 10] 0:0.3:2 [0 0.3 0.6 0.9 1.2 1.5 1.8]
Dimensional range: a(2, 1:2) [4 5] a(2:3, 1) [4; 7] a(2, : ) [4 5 6] row vector a(:, 1) [1; 4; 7] column vector a(:, : ) == a
54
a = [1:4; 5:8; 9:12; 13:16] 4x4 array Pick out rows 1 and 3:
a([1 3], : ) 1 2 3 4 9 10 11 12
Matrices can be treated as vectors, withelements ordered columnwise:
a(1:3:16) = 0a(1:2:16) = [8 7 6 5 4 3 2 1]a(16:-4:1) = 1.1*(1:4)
55
Arrays can have more than two dimensions e.g. A(l, m, n)
Can be created in several ways: Extension of 2-d array:
A = [1 2 3; 4 5 6; 7 8 9];A(:, :, 2) = [9 8 7; 6 5 4; 3 2 1];
A(:, :, 3) = 5; Using Matlab functions:
A = randn(4, 3, 2)
56
u = [3; 1; 4]; 3x1 column vector
v = [2 0 -1]; 1x3 row vector Inner product:
x = v * u 2 1x3 x 3x1 1x1(also known as “scalar product” and “dot product”)
Outer product:x = u * v 6 0 -3
2 0 -18 0 -4 3x1 x 1x3
3x3 Cross product:
x = cross(u, v) [-1 11 -2]
57
Here we want to solve the system of linear equations represented by A x = b
Use the “\” operator to do “left-division”:A = [1 2 3; 4 5 6; 7 8 10];b = [1; 1; 1];x = A \ b -1.0000
1.0000 0.0000
r = b – A * x small numbers! When m > n (over-determined), “\” least-squares solution. When m < n (under-determined), “\” a particular solution.
General solutions can be found using null(A).
58
Arguments specified using round brackets and commas: e.g. atan2(y, x)
Return values can be assigned to a scalar, an array, or to an array of variables. e.g. a = [1 2 3; 4 5 6];
size(a) [2 3]mn = size(a)[m n] = size(a)
59
Trigonometry: sin, cos, tan, atan, atan2(y, x)
Exponential: log, log10, exp, sqrt Complex: abs, conj, real, imag, complex Rounding: fix, floor, ceil, round Matrix functions
linspace, logspace, zeros, ones, eye reshape, size, length expm, logm, sqrtm sum, prod, diag, norm, det, inv, eig
Random numbers: rand, randn
60
There are two kinds of M-files: Scripts
Automate a series of steps you need to perform many times
Have no input arguments or return values Operate on data in the workspace.
User-defined Functions Extend the Matlab language for your
application Can accept input arguments and return
output arguments Internal variables are local to the function 61
function f = fact(n) Definition line
% Compute a factorial value. H1 line
% fact(n) returns the factorial of n, Help text
% usually denoted by n!% Put simply, fact(n) is prod(1:n) Commentf = prod(1:n); Function body By convention, name the m-file “fact.m”
62
Upper and lower case characters are not equivalent (MATLAB is case sensitive).
Typing the name of a variable will case MATLAB to display its current value.
MATLAB uses parenthesis, ( ), square bracket [ ], and curly braces { }, and characters followed by up arrow.
You can type help topics to access online help on the command, functions or symbol topic. Note that hyperlinks, indicated by underlines, are provided that will take you to related help items and the Help browser.
If you press the tab key after partially typing a function or variable name, MATLAB will attempt to complete it, offering you a selection of choices if there is more than one possible completion.
You can quit MATLAB by typing exit or quit.
63
63
64
64
Weakness of MATLAB
Interpreter – slower than compilers
Clumsy in handling texts Finite-precision arithmetic Infinite-precision in symbolic
computations, but slow Expensive – scilab project