Basics Of Matlab - WPI Wiki

Transcription

Basics of MatlabAdriana Heraahera @wpi.edu- 2013-Reference: Matlab documentation1

MATLAB Course1. Getting started; Matlab Help;2. Variables;3. Operators;4. Matlab functions;5. Matrices;6. Scripts;7. Basic plotting.8. User Defined Functions9. Importing Data10. Simulink11. Flow Control Commands2

Where to find Matlab?1. Matlab is installed on all computers in the public labs (i.e. HL230,library, etc)2. To install Matlab on your personal computer go Installs/matlab.htmlor google for WPI Matlab3. Run Matlab on the terminal server windows.wpi.edu with RemoteDesktop or using Virtual Lab Web re/termserv.html3

Additional Matlab Resources and TrainingMatlab Lecture Notes at blackboard.wpi.edu SESA TrainingTo access SESA Training web site:1. Log in to the blackboard.wpi.edu2.Once you have logged into Blackboard, click on theCommunity tab at the top of the page3.In the 'Organization Search' text box typeSESA andclick "Go".4.5.The organization information will be displayed in theSearch Results. Click the down arrows located to theright of the Organization ID and then click on EnrollAn "Action Successful" enrollment message will appearon the screen. Click the OK button to access theorganization. Registration at:http://www.wpi.edu/Regi/CCC/sesa.html Customized Matlab training sessions, ifmore than 5-7 students are interested in.4

Matlab ResourcesMATWORKS web siteTutorials on Specific Topics and FeaturesEach video shows a specific feature or application example. Topics range from basic to examples.html (MATLAB Overview, Getting Started, Mathematics,Graphics and Visualization, Programming)Interactive MATLAB & Simulink Based TutorialsAn interactive video-based tutorial that introduces MATLAB capabilities and programmingGetting Started (Tutorials for t version/start.htmlMATLAB recorded binars/index.htmlIntroduction to MATLAB (for beginners)Short Simulink /examples.htmlMATLAB CentralYou can learn more about how MathWorks products are used by visiting MATLAB eriments with MATLAB, by Cleve MolerOnline textbook that introduces MATLAB through the use of interesting puzzles and s.html?s cid edu cr 15325

What is Matlab ?MATLAB is a high-performance language for technical computing.It integrates computation, visualization, and programming in an easy-touse environment where problems and solutions are expressed in familiarmathematical notation.MATLAB stands for matrix laboratory.MATLAB is an interactive system whose basic data element is an matrix(array) that does not require dimensioning.This allows you to solve many technical computing problems, especiallythose with matrix and vector formulations, in a fraction of the time it wouldtake to write a program in a scalar non-interactive language such as C orFortran.6

MATLAB System1. The MATLAB Language(matrix language with loops, functions, data structures.)2. Development Environment(desktop, windows, browsers,.)3. The MATLAB Mathematical Function Library; Toolboxes4. Graphics (datavisualization, image processing, animation)5. The MATLAB External Interfaces (API)(alibrary that allows you to write C and Fortran programsthat interact with MATLAB)7

Starting Matlab Windows: Start menu Matlab Matlab Unix: Terminal window type matlab8

Matlab WindowMenuCurrent DirectoryCommand WindowWorkspace WindowHistory Window9

Matlab Help1. Using HELP menu MATLAB HelpHELP Using Help Browser2. helpdeskOpens the Help browser.3. help commandname/toolboxname/functionnameEx: help sin4. doc commandname/toolboxname/functionnamedisplays the detailed info in the Help browser.Ex: doc sinOther commands:5. lookfor helpdesk - search10

I. Matlab Programming Matlab Variables Numbers Operators Functions .11

Matlab VariablesA MATLAB variable is essentially a tag that you assign to a value in memory.MATLAB does not require any type declarations or dimension statements.When MATLAB encounters a new variable name, it automatically creates thevariable and allocates the appropriate amount of storage.If the variable already exists, MATLAB changes its contents.Variable names consist of a letter, followed by any number of letters, digits, orunderscores.MATLAB uses only the first 31 characters of a variable name.MATLAB is case sensitive; it distinguishes between uppercase and lowercaseletters.MATLAB stores variables in a part of memory called workspace.To view what is stored in a variable type its name.Types of Variables:MATLAB provides three basic types of variables:Local VariablesGlobal VariablesPersistent Variables12

Matlab VariablesRules for variable names:Syntax: Make Sure Variable Names Are ValidvarialeName Value; Don't Use Function Names for Variables Check for Reserved Keywords Avoid Using i and j for VariablesExample: a 5; b 7; c a bHow to remove a variable from workspace: method ‘linear’ clear variableName clear- removes all variables from the workspace (!!!!)ans default variable, when the result is not assign to a variableExercise: 1. Definea1 8 and b2 8, c1 a1 b22. Other commands:variable input(‘prompt’) a3 input(‘a3 ‘)( help input)13

Numbers1. IntegersMatlab has 8,16,32, 64 bit , signed and unsigned integer data types.(int8, int16, int32, int64, uint8, uint16, uint32, uint64)2. floating-point numbers:in either double-precision (64 bits)or single-precision (32 bits) format.(double, single)3. Imaginary numbers use either i or j as a suffixEx: 5 2i6 -3.14159j4. Infinity and NaNUseful related functions:realmax , realmin, intmin , intmax, epsisnan, format14

Numberseps – function that returns the distance from 1.0 to the next largest doubleprecision numberd eps(X) is the positive distance from abs(X) to the next larger inmagnitude floating point number of the same precision as X.infInfinity : division by zero and overflow, which lead to resultstoo large to represent as conventional floating-point values.ex: 1/0, 1.e1000NaNNot-a-Number: a result of mathematically undefinedoperations like 0.0/0.0 and inf-inf.Related commands: edit15

Numbers1. - decimal notation (with an optional decimal point and leading plus or minus sign)Ex:3-990.00012. . Scientific notation (uses the letter e to specify a power-of-ten scale factor.)Ex: 1.60210e-56.02252e10All numbers are stored internally using the long formatspecified by the IEEE floating-point standard. Floatingpoint numbers have a finite precision of roughly 16significant decimal digits and a finite range of roughly10-308 to 10 308.Useful related functions:realmax , realmin, intmin , intmax, epsisnan, format16

Strings name ‘John’% create a string variable errorMessage ‘negative number’Useful related functions: num2str,str2num, strcat17

OperatorsExpressions use familiar arithmetic operators and precedence rules.18

Functions1. Standard elementary mathematical functions help elfunTrigonometric (sin, cos)Exponential (exp, log)Complex (abs, angle)Rounding and remainder (round)2. Elementary matrices and matrix manipulation. help elmat3. Specialized math functions.help specfun19

Functions1. Built-in functions (Ex. sqrt, sin)Some of the functions, like sqrt and sin, are built in.Built-in functions are part of the MATLAB coreThey are very efficientThe computational details are not readily accessible.(you cannot see the code)2. Function implemented in M-files (ex.factorial, mean, det)You can see the code and even modify it, if you want.Syntax: outputArgs functionName(inputArgs)Related commands: edit20

I. Matlab ProgrammingWe talked about: Matlab Variables Numbers Operators Functions21

III. Matlab Programming . Matrices Operators Functions .22

Matrix & basic matrix functionsDefine a matrix:1. Type the matrix2. Use Specialized Matrix FunctionsMatrix ManipulationMatrix Functions23

Matrix: Define a matrix1. Type the matrixSeparate the elements of a row with blanks or commas.Use a semicolon, ; , to indicate the end of each row.Surround the entire list of elements with square brackets, [ ]. 1 2 3 A 21 22 23 31 32 33 1. A [1 2 3; 21 22 23; 31 32 33];2. A [1, 2, 3; 21, 22, 23; 31, 32,33];3. A(1,1) 1; A(1,2) 12; A(1,3) 13; A(2,1) 21; A(2,2) 22;A(2,3) 23;Basic matrix information:size(size of a matrix) [m,n] size(X)24

Matrix: Define a matrix2. Use Specialized Matrix Functions B eye(3) C ones(2,3)D B C 0.42891001110100.30461110010.18970.1934 D rand(4,1)25

Matrix: Accessing Matrix Elementsindividual elementans A(2,2)22ans column 1 2 3 A 21 22 23 31 32 33 :2A(:,2)(colon) all elements2232row A(2,:)ans 212223group of elements A(2,1:2)ans 2122first element : step: last element26

Matrix: OperationsA BA-BA*BA/BA\BA BA'A.*BA./BA.\BA. BA.'27

Matrix: Operations 1 2 3 A 2 3 1 , 2 2 2 10 20 30 B 11 21 31 , 1 2 3 A [1 2 3; 2 3 1; 2 2 2]; A*Bans 3568101541051564486128 B [10 20 30; 11 21 31; 1 2 3]; a11 a12 a13 b11 b12 b13 A a21 a22 a23 ,B b21 b22 b23 , a31 a32 a33 b31 b32 b33 a11 b11 a12 b12 a13 b13 A *B a21 b21 a22 b22 a23 b23 a31 b31 a32 b32 a33 b33 A.*Bans 104090226331246Element by element multiplication28

Matrix: FunctionsFew matrix functions :det-Determinanttrace-Sum of diagonal elementslinsolve-Solve linear systems of equations (using LU factorization)eig- Find eigenvalues and eigenvectorseigs -Find largest eigenvalues and eigenvectors of a sparse matrixsdv- Singular value decompositionbalance -Improve accuracy of computed eigenvalues\- Linear equation solution(X A\B is the solution to the equation AX Bcomputed by Gaussian elimination)cond – condition number (the ratio of thelargest singular value to the smallest) doc elmat29

Matrix: Solution of a linear systemX A\B is the solution to the equation AX Bcomputed by Gaussian eliminationx1 x2 x3 2x1 2 x2 3x3 5x1 3x2 6 x3 7x1 ?x2 ?x3 ?A square matrix\ ldivide A [1,1,1;1,2,3;1,3,6]; b [2;5;7];1. x A\b2. x linsolve(A,b)3. x inv(A)*bX -25-1(X A\B is the solution to the equation Ax b computed by Gaussian elimination)linsolve-Solve linear systems of equations (using LU factorization)30

III. Matlab ProgrammingWe talked about: . Matrices Operators Functions .III. How to write a program (M-files)IV. How to plot data31

M-filesFiles that contain code in the MATLAB language are called M-files.You create M-files using a text editor.Use a M-file as any other MATLAB function or command.A M-file is a plain text file.Two kinds of M-files:Scriptsdo not accept input arguments or return output argumentsoperate on data in the workspace.Functionscan accept input arguments and return output argumentsinternal variables are local to the function.32

M-files: Scriptsdo not accept input arguments or return output argumentsoperate on data in the workspace.%myScript edit myScripttype the codeExample% this is my script fileFile/Save% calculates the determinant of A myScriptclear(to run the script type its name)N 10;theta pi/N;r sin(theta);% - indicates a comment33

Matlab - e plot function has different forms, depending on the inputarguments.If y is a vector, plot(y) produces a piecewise linear graph of theelements of y versus the index of the elements of y.If you specify two vectors as arguments, plot(x,y) produces agraph of y versus x.34

Matlab - Plottingplot(x,y, s);sallows to plot : colors, symbols, different ark-.dashdotccyan plus--dashed*star(none) no linemmagentayyellowssquarekblackddiamond .plot (x,y,'c :')plots a cyan dotted line with a plus at each data point;35

Matlab - Plottingcleart 0:0.01:10; % time secondssignalSin sin(2*pi*t); % signal1 - frequency 1 HzsignalCos 0.5*cos(2*pi*t); % signal2 - frequency 1 Hzfigureplot(t,signalSin);plot2signals.mhold onplot(t,signalCos, '-*r');xlabel('time'); ylabel('signal');legend('Sin', 'Cos');title('Two Signals','FontSize',12)Other commands:xlabelfigureylabellegend,title36

Matlab - PlottingTwo 1012345time67891037

Matlab - Plotting P1 [1,2];P2 [3,4];P3 [3,6];line([P1(1), P2(1), P3(1)], [P1(2), P2(2), P3(2)])38

Visualization - Interactive editingshow plot tools39

Visualization - subplot subplot(3,1,1) 1subplot(m,n,q) subplot(3,2,4)10* breaks the figure into a m x n matrixof windows.2q the current window1340.5000.51plot3Windows.m5640

Visualization - subplotclear; % clear the workspaceclose; % close previous figuresSignalSin1signal% Generate the signalst 0:0.02:10; % time seconds0signalSin sin(2*pi*t); % signal1 - frequency 1 Hz-1signalCos 0.5*cos(2*pi*t); % signal2 - frequency 1 Hz0123456time(s)SignalCos78910signal0.5% Plot the signalsfigure; subplot(3,1,1)0plot(t,signalSin,'-ok', s)Product of two plot(3,1,2)0.2signalsignal3 signalSin.*signalCos;plot(t,signalCos, bplot(3,1,3)plot(t,signal3);gridtitle('Product of two ([0 10 -0.3 0.3]); % sintax: axis([XMIN XMAX YMIN YMAX])

Introduction to MATLABSUMMARY1. Getting started; Matlab Help;2. Variables;3. Operators;4. Matlab functions;5. Matrices;6. Scripts;7. Basic plotting.8. User Defined Functions9. Importing Data10. Simulink42

FUNCTIONS Matlab functions & ToolboxesUser Defined FunctionsThere are essentially two ways to create a new functionin MATLAB:1. in a file saved to permanent storage. ( .m file )2. in a command entered at run-time (inline, anonymous)43

FUNCTIONSFunctions are M-files that can acceptinput arguments and return outputarguments.The M-file and function should havethe same name.Each M-file function has an area ofmemory, called the function workspace,separate from the MATLAB baseworkspace, in which it operates.Input ArgumentsfunctionName. mOutput Arguments44

FUNCTIONSFunction definition:input argumentsOutput argumentsfunction [x, y] day2Fun(A,alpha, f, t);keywordfunctionfunction nameCalling the function: [x1, y1] day2Fun (A1,alpha1, f1,t1);45

FUNCTIONSFunction definition:day2Fun.mfunction [x, y] day2Fun(A,alpha, f, t);exampleFun.m%% function [x, y] day2Function(A,alfa, f, t);%% Lecture2: user defined functions in Matlabamplitude A*exp(-alpha*t);x amplitude.*sin(2*pi*f*t);y amplitude.*cos(2*pi*f*t);Main code figure plot(t1,x1, t1,y1); legend('x1', 'y1')clear allA1 5;alpha1 0.5;f1 1;t1 0:0.01:10;[x1, y1] day2Fun(A1,alpha1, f1, t1);46

Function: Input and output argumentsfunction [x, y] day2Fun(A,alpha, f, t); [x1, y1] day2Fun (A1,alpha1, f1, t1);Matlab WorkspaceFunction WorkspaceLocalInput argumentsA1, alpha1, f1, t1A,alpha, f, t,other fun variablevariablesOutput argumentsx1, y1Global variablesGlobal variables:day2Fun2.mexampleFun2.mx, yGlobal variablesShared workspace47

FUNCTIONS: How to document a functionthe function-declarationlinekeyword functionfunction name traceorder of arguments.function t trace(a)%TRACESum of diagonal elements.%TRACE(A) is the sum of the diagonal elements of A,which is%also the sum of the eigenvalues of A.The%%%Class support for input A:float: double, singletext%Copyright 1984-2004 The MathWorks, Inc.% Revision: 5.8.4.1 t sum(diag(a));help Date: 2004/04/10 23:30:11 executable code trace(A) results trace(A);48

Function: Inline functionsThere are essentially two ways to create a new function inMATLAB:1. in a command entered at run-time (inline and anonymous)2. or in a file saved to permanent storage.inline function,feval f inline('x 2 y 2‘, ‘x’, ‘y’)f Inline function:f(x,y) x 2 y 2 m f(1,2)m 549

1.1 Importing and Exporting Data1.1.2 Supported File Formats50

1. Importing and Exporting Data using the Import Wizard save , load dlmread , dlmwrite xlsread, xlswrite fopen, , fscanf, fprintf51

1.1 Importing and Exporting Data1.1.1 Using the Import Wizard with Text DataFile Import Dataor uiimport1.1.2 Supported File FormatsWizard: missing data: NaN (Not-a-Number.)52

1.1 Importing & exporting data: dlmread & dlmwritedlmread , dlmwrite -Read/Write ASCII delimited file.prepareData.mfileNamematrix to be savedadd at the end ofexisting filedata dlmread(‘myFile’);dlmwrite(fileName, data,'delimiter', '\t', '-append');dlmwrite(fileName, data, '\t')Delimiter tabdata dlmread('dataCSV.csv', ',',2,0);dlmread reads from the ASCII-delimited numeric data file filename to output matrixM. The delimiter separating data elements is inferred from the formatting of the file.Comma (,) is the default delimiter.53

1.1 Importing & exporting data: dlmread & dlmwritedlmread , dlmwrite -Read/Write ASCII delimited file.for i 1:4fileName ['results', num2str(i), '.csv']data(i,:,:) dlmread(fileName, ',',2,0);end54

1.1 Importing & exporting data: xlswrite, xlsreadxlswrite, xlsread - Write/Read Excel file.xlswrite('filename', data)xlsread('filename')To import Excel data by wizard (uiimport) the file should have the extension .xls55

SIMULINK56

SIMULINKSimulink is software for modeling, simulating, and analyzing dynamic systems.It supports linear and nonlinear systems, modeled in continuoustime, sampled time, or a hybrid of the two.Systems can also be multirate, i.e., have different parts that are sampled or updatedat different rates.For modeling, Simulink provides a graphical user interface (GUI) for building modelsas block diagrams, using click-and-drag mouse operations. simulink

Response of a SDOF (nDOFs) systemKCx(t)M 1f(t)58

Linear systems: time and laplace domainsTimeDomainx1 xx2 x x 1 x Cd x Kx f (t )x(t0 ), x (t0 )x 1 x2x 2 Cd x2 Kx1 f (t )y xF(s)LaplaceDomainH ( s) 1s 2 Cd s K X(s)1 x1 0 x 1 0 x K C x 1 f (t )d 2 2 x y 1 0 1 0 f (t ) x2 x Ax Bfy Cx Dfparameters.m59

Linear systems: time and laplace domains x Cd x Kx f (t )x(t0 ), x (t0 )TimeDomainAB1 x1 0 x 1 0 x K C x 1 f (t )d 2 2 x1 y 1 0 0 f (t ) x2 C y xx Ax Bfy Cx DfDparameters.m60

Example 1:61

0) Start simulinkExample 1:3)1)2)4)5) Run the model62

Another approach:Example 2:

Loops (Flow Control)MATLAB has several flow control commands:if, else, and elseifswitch and caseforwhilecontinuebreakreturn64

Flow Control: if elseif :conditionally executes statementsif relationa 5; b 7;statements 1elseExample:if a bdisp('a greater than b');statements 2endelsedisp('b greater than a');endif elsestatements3end65

Flow Control: forThe for loop executes a group of statements a number of times.for variable expressionExample:for n 1:5r(n) n 2;statementsendendrexpression:first value: last valuefirst value: step: last valueChange of increment:for n 1:2:10; statement; end;for n 10:-1:1; statement; end;66

Flow Control: whileThe while loop executes a group of statements until a logical test isfalse.while expressionstatementsendExample:a 1;while a 0.1a randendOther commands:rand67

Flow Control: switch, caseEx: Find the structure of the command. help switchMy Example: doc switchfiles: exSwitch.mcleara 6; b 2;method input(' method ')

6 MATLAB is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to- use environment where problems and solutions are expressed in familiar mathematical notation. MATLAB stands for matrix laboratory. MATLAB is an interactive system whose basic data element is an matrix (array) that does not require dimensioning.