Introduction to MATLAB

download Introduction to MATLAB

of 36

description

basic matlab

Transcript of Introduction to MATLAB

  • Introduction to MATLABMATLAB in Science, Engineering, and Mathematics Instruction

    John SebesonDeVry University

    J. M. Sebeson - DeVry University 2005

  • What is MATLAB?MATLAB stands for MATrix LABoratory. MATLAB is a high-performance language for technical computing.Math and computation Algorithm development (optimized for DSP)Data acquisition Modeling, simulation, and prototyping Data analysis, exploration, and visualization Scientific and engineering graphics Application development, including graphical user interface building

    J. M. Sebeson - DeVry University 2005

  • Why Learn and Use MATLAB?Heavily used in EET/CET courses with DSP content (CET311, EET350, EET453)Extensive built-in commands for scientific and engineering mathematicsEasy way to generate class demonstrations and test examples Simple and intuitive programming for more complex problemsStandard and widely-used computational environment with many features, extensions, and links to other software.

    J. M. Sebeson - DeVry University 2005

  • MATLAB in DSP Product DevelopmentDevelop and Test Algorithms in MATLABSIMULINK SimulationCode ComposerDSP Processor PlatformMATLAB + PC = DSP Processor!! (just less efficient)

    J. M. Sebeson - DeVry University 2005

  • Why Learn MATLAB (and DSP)?Digital Signal Processing (DSP) is the dominant technology today, and into the future, for small-signal electronic systems (i.e., just about everything)MATLAB has become one of the standard design environments for DSP engineeringOur students need to be literate and skilled in this environment: knowledgeable in both DSP and MATLAB

    J. M. Sebeson - DeVry University 2005

  • How Can I Learn MATLAB?Keep a copy of this presentation for reference (available on my Web Page)Get MATLAB loaded on your PCRead the Getting Started Users Guide at the MathWorks web siteStudy some of the built-in help files and demosDive right in and use it!

    J. M. Sebeson - DeVry University 2005

  • This PresentationThe MATLAB SystemThe basics of MATLAB computationThe basics of MATLAB graphingThe basics of MATLAB programmingVarious course examplesMathematicsElectronicsPhysicsSignal Processing(*)

    J. M. Sebeson - DeVry University 2005

  • The MATLAB SystemDevelopment Environment. MATLAB desktop Editor and debugger for MATLAB programs (m-files)Browsers for help, built-in and on-line documentationExtensive demos The MATLAB Mathematical Function Library. Elementary functions, like sum, sine, cosine, and complex arithmetic More sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms. Toolboxes for special application areas such as Signal ProcessingThe MATLAB Language. Programming in the small" to rapidly create quick and dirty throw-away programs, or Programming in the large" to create large and complex application programs. Graphics. 2D and 3D plotsEditing and annotation featuresThe MATLAB Application Program Interface (API). A library that allows you to write C and Fortran programs that interact with MATLAB.

    J. M. Sebeson - DeVry University 2005

  • MATLAB Development Environment (Workspace)

    J. M. Sebeson - DeVry University 2005

  • MATLAB Help UtilitiesMATLAB is so rich that help is essentialCommand name and syntaxCommand input/output parametersUsage examplesHelp commandhelp command_namehelp [partial_name] tabHelp documentsDemos

    J. M. Sebeson - DeVry University 2005

  • MATLAB Function Library (A Subset)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.

    J. M. Sebeson - DeVry University 2005

  • Some Elementary Functions Exponential.

    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. realpow - Power that will error out on complex result. reallog - Natural logarithm of real number. realsqrt - Square root of number greater than or equal to zero. sqrt - Square root. nthroot - Real n-th root of real numbers. nextpow2 - Next higher power of 2.

    J. M. Sebeson - DeVry University 2005

  • Some Specialized FunctionsNumber theoretic functions.

    factor - Prime factors. isprime - True for prime numbers. primes - Generate list of prime numbers. gcd - Greatest common divisor. lcm - Least common multiple. rat - Rational approximation. rats - Rational output. perms - All possible permutations. nchoosek - All combinations of N elements taken K at a time. factorial - Factorial function.

    J. M. Sebeson - DeVry University 2005

  • The MATLAB Language (M-file example)function one_period(amp,freq,phase)% ONE_PERIOD(AMP,FREQ,PHASE)% This function plots one period of a sine wave with a given amplitude,% frequency (in Hz), and phase ( in degrees).T=1000/freq; % Compute the period in mst=0:T/100:T; % Define a 100 point ms time vector 1 period longy=amp*sin(2*pi*t/T+phase*pi/180); % One period of the sine functionplot(t,y) % Plot the result and format the axes and titlexlabel('milliseconds')ylabel('amplitude')title(['One Period of a ',num2str(freq),' Hz Sinewave with ',num2str(phase), ' Degree phase'])

    J. M. Sebeson - DeVry University 2005

  • MATLAB Graphics:2D Functions (Physics Example)

    J. M. Sebeson - DeVry University 2005

  • MATLAB Graphics:2D Functions (Physics Example)

    J. M. Sebeson - DeVry University 2005

  • MATLAB Graphics:3D Functions (DSP Example)

    J. M. Sebeson - DeVry University 2005

  • Basic MATLAB Computation:Representation of Numbers and VariablesMATLAB operates on n row by m column matrices:A n x m quantity is an array

    A 1 x m or a n x 1 quantity is a vector[8 1 6]A 1 x 1 quantity is a scalar[8]

    [8 1 6 3 5 7 4 9 2]

    J. M. Sebeson - DeVry University 2005

  • Basic MATLAB Computation:Basic OperationsArray manipulation (Magic Square example)Sum, diag, transpose, colon operator, indexingArray, vector, and scalar operatorsMatrix and vector addition and multiplicationElement-by-element operationsVariable statements and definitions

    J. M. Sebeson - DeVry University 2005

  • MATLAB Plotting and GraphicsRich set of commands for 2D and 3D plotting of functionsCommand formatting and editingGUI formatting and editingImage display capabilitiesAnimation capabilitiesSimple copy and paste for publishing generated figures

    J. M. Sebeson - DeVry University 2005

  • MATLAB PlottingBasic Commandsplot x,y line plotsstem n,y discrete plots (standard representation of digital signals)bar vertical bar plotsplot3 3D x,y,z line plotsmesh, surf, etc. 3D surface plots show_img display matrix as an imagehold hold current figure for multiple line plotssubplot put multiple plots in one figure frameEtc, etc. - See MATLAB help documentation

    J. M. Sebeson - DeVry University 2005

  • Basic Plotting - ExamplesPlot of sin(x) functionStem of sin(x) functionBar of sin(x) functionSeveral sine functions with holdSeveral sine functions with subplot2D plot of sinc(x)3D plot of sinc(x) [plot_sinc m-file]GUI editingView by rotationAnimation [brownian_demo m-file]

    J. M. Sebeson - DeVry University 2005

  • Basic MATLAB ProgrammingScriptsString of MATLAB commandsStored as m-file (*.m)Use variables from command lineVariables have names consistent with script variable namesUsed for quick and dirty programsExample: dydx_scriptFunctionsString of MATLAB commandsStored as m-file (*.m)Use variables as function parametersNo restriction on parameter namesCan return variable resultsUsed for general purpose programsExample: yy=dydx(x,y)

    J. M. Sebeson - DeVry University 2005

  • Structure of m-file Functions:Examplesone_periodUse of num2str for variable formattingsumofsinesUse of parameter-controlled data input loopsfft_plotUse of MATLAB functions as subroutinesUse of nargin test and branch

    J. M. Sebeson - DeVry University 2005

  • Mathematics Example:Polynomial Algebra (Convolution Operator)Polynomial products and factoring:

    >> p1=[1,3,2];>> p2=[1,5,4,4];>> pc=conv(p1,p2)pc = 1 8 21 26 20 8>> deconv(pc,p2)ans = 1 3 2>> deconv(pc,p1)ans = 1 5 4 4

    J. M. Sebeson - DeVry University 2005

  • Mathematics Example:Linear SystemsSolve the system:

    A*S=BMATLAB Code:

    >> A=[5,-2,-3;0,4,3;1,-1,9];>> B=[-3,-2,60]'; % Note vector transpose ()>> S=linsolve(A,B)S = 1.0000 -5.0000 6.0000

    J. M. Sebeson - DeVry University 2005

  • Mathematics Example:Polynomial RootsFind the roots of the following system:

    MATLAB code:

    >> roots([12 -1 -8])ans = 0.8592 -0.7759

    J. M. Sebeson - DeVry University 2005

  • Mathematics Example:Polynomial RootsGraphical Solution:

    >> a=12;>> b=-1;>> c=-8;>> x=-1:0.1:1;>> y=a*x.^2+b*x+c;>> plot(x,y)

    J. M. Sebeson - DeVry University 2005

  • Electronic Circuits Example:Mesh Analysis (Linear System)Find the currents in each branch: I1, I2-7I1 + 6I2 = 56I1 8I2 = -10>> A=[-7,6;6,-8];>> B=[5;-10];>> X=linsolve(A,B)ans = 1.0000 2.0000A*X = B

    J. M. Sebeson - DeVry University 2005

  • Electronic Circuits Example:FET Operating PointFind the DC operating point of the following circuit:

    J. M. Sebeson - DeVry University 2005

  • Electronic Circuits Example:FET Operating PointM-file: [Vgs_o,Id_o]=NFET_OP(Idss,Vp,Rs)[v,id]=nfet_op(12,-4,1200);

    J. M. Sebeson - DeVry University 2005

  • Physics Example:Graphical Solution of a TrajectoryProblem:A football kicker can give the ball an initial speed of 25 m/s. Within what two elevation angles must he kick the ball to score a field goal from a point 50 m in front of goalposts whose horizontal bar is 3.44 m above the ground?

    J. M. Sebeson - DeVry University 2005

  • Physics Example:Field Goal ProblemSolution: The general solution is the trajectory equation.

    where y = height, x = distance from goal, v0 = take-off speed, 0 = take-off angle. Given the take-off speed of 25 m/s, the problem requires the solutions for 0 that result in a minimum height of y = 3.44 m at a distance of x = 50 m from the goal post. Although an analytical solution is possible, a graphical solution provides more physical insight.

    J. M. Sebeson - DeVry University 2005

  • Physics Example:Field Goal ProblemMATLAB code for a graphical solution:

    >> v0=25;>> x=50;>> g=9.8;>> y=3.44;>> theta=5:.1:70;>> theta_r=theta*pi/180;>> z=y*ones(1,length(theta));>> zz=x*tan(theta_r)-g*x^2./(2*v0^2*(cos(theta_r)).^2);>> plot(theta,zz)>> holdCurrent plot held>> plot(theta,z)

    J. M. Sebeson - DeVry University 2005

  • Physics Example:MATLAB Results

    J. M. Sebeson - DeVry University 2005

  • Signal Processing ExamplesFourier Synthesis and the Gibbs Phenomenonsquare_jms m-file

    Finite Impulse Response (FIR) Filter Design

    Use of fvtool

    Analog-to-Digital Converter Emulationadc m-file

    Digital Transfer Function in the Z-domainplotH m-file

    J. M. Sebeson - DeVry University 2005