You are on page 1of 46
/ oy MATLAB Workshop 201) MATLAB - An Introduction fe environment that enables you to perform MATLAB is a high-level language and interactive han with traditional programming languages such as computationally intensive tasks faster and easier tl C, C4, and FORTRAN, The MATLAB high-performance language for technical computing integrates computation, vsvaletion, and programming in an easy-to-use environment whete problems and solutions are expressed in familiar mathematical notation. Typical uses Include > Math and computation > Modeling, simulation, and prototyping > Algorithm development > Data analysis, exploration, and visualization > Date acquisition >> Scientific and engineering graphics > Application development, including ‘graphical user interface building AB to (ATI MATLAB (Matrix Laboratory) was invented by Cleve Moler (the then Chairman CS Dept., Univ of New Mexico) to give his students access to LINPACK and EISPACK without having to learn Fortran. LINPACK is a software library for performing numerical linear algebra on digital computers while EISPACK is a software library for numerical computation of eigenvalues and eigenvectors of matrices, written in FORTRAN Cleve Moler, Jack Little and Steve Bangert rewrote MATLAB in C and founded The MathWorks in 1984 to continue its development. These rewritten libraries were known as JACKPAC. In 2000, MATLAB was rewritten to use a newer set of libraries for matrix manipulation, LAPACK(Linear Algebra PACKage, a software library for numerical linear algebra). Today, MATLAB engines incorporate the LAPACK and BLAS libraries, embedding the state of the art in software for matrix computation, ‘The MATLAB System The MATLAB system consists of these main parts: > Desktop Tools and Development Environment - set of tools and facilities that help you use and become more productive with MATLAB functions and files, > Mathematical Function Library - a vast collection of computational algorithms ranging from elementary functions, like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inveise, matrix EIGENVALUES, Bessel functions, and fast Fourier transforms > The Language - a high-level matrix /array language with control flow statements, functions, data structures, input/output, and object-oriented programming features > Graphics - for displaying vectors and matrices as graphs, 2s well as annotating and printing these graphs. It includes high-level functions for two-dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. > External Interfaces- allows writing C and FORTRON programs that interact with MATLAB. It includes facilities for calling routines from MATLAB (dynamic linking), for calling MATLAB as computational engine, and for reading and writing MAT-files. Copyright © by IEEE Student Branch, UET Lahore. This material eclusively forthe use of student of MATLAB Workshop 2031 organized by IEEE WIE Affinity Group snd IGEE Student Branch, University of Engineering & Technology, Lahore Of 13 Warkshop 2012 Getting Started with MATL, AB ae > Se ai aie WaiLAs pig an A a louble-licking the MATLAB shortcut B®” on your Window personal computer oF bi mon You cant 0 install Trial software on your > When you start MATLAB, the deskt managing files, variables, atom ear and application re, Containg tols(graphieal user interfaces) for NS associated with Martian Statements clp hecurent " — Cocimentaton inte Sie Mader ep WATE war © cemem eiaer Monte ca Previous Commands Start Menu click to see options > When you start MATLAB, by default, MATLAB automatically loads all the program files provided by The MathWorks for MATLAB and othey MathWorks products like Simulink, > Inthe Command Window, the MATLAB prompt (1) indicates where the commands are entered, Anything you see after this prompt denotes user input (Le. a command) followed by a carriage return (i.e. the “enter” key]. Often, input is followed by output so unless otherwise specified the line(s) that follow a command will denote outout, Copyright © by gEE Student Branch, UET Lahore This materials exclusively forthe use of student of MATLAB Workshop 2012, ‘organized by IEEE WIE Affinity Group and IEEE Student Branch, Unversity of Engineering & Technology, Lahore ee IEEE Variables, Number Te > MATLAB is an interactive system whose bas! dimensioning, 1 the can.mand window try the fo inputs after prompt (>>) and wateh output. >pael >> be2 Where a, b, candd are the variables. In Matlab, you don’t have to separately declare the variables, Rather you construct commands by using the variables. You can see the variables and their values in Workspace Window. > Write the following commands and see their output, Compare it with the output shown below. >> ceatb >> decos(a) Where a and b have (he values defined previously (a=1 and b=2) while the result of arb and cos(a} is stored in the auress spaced defined by c and d. whenever you use a variable, some address space is allocated toit.. ic deta element is an array that does not require lowing commands i.e. write the following j aac tice so%x{| watch the [Dienst mca anes */ Ses DWH [ance |Dse. ~ variables oH and the : : Workspace Window Previous commands appe in this window @ can be executec dragging them t command wind ‘Tips & Tricks Output is not echoed if a Semicolon placed at the end of « command ie. ifa semicolon is icolon, ;, is pl of ie i cc placed at the énd of © command, the command is executed by hitting the carriage return b fae ° ah in ‘ioge return but its IEEE eee sg enna at 0H OU sn w oro the Se avses pon stot git a vale, MATLAB ge the vate short for anges spoowe ata cateulation, Wa vale fs assigned « new vaio, It would replace its previous valve © Sayed ane 0 » MATAR CaN ge NOmensional arnays soto 2348) ines an array(vector) of 8 elements, The elements of artay ily, the following command would create a Matrix of order 33. trices anvay based language whose varlable ean be vectars (one dirmenstomal array), Ma are rvrlosed In square brad sete 235456) 7 820] J plus or minus sign, for floating-point standard. 4a finite range of roughly conventional decimal notation, with an aptionsl decimal olin ane fading ‘Ail mers ae stored internally using the long format specified by We IEEE® infers have a finite precision of roughly 16 significant decimal diits a4 es the letter to spesify a power-ofen cee factor, Imaginary numbers use either ior 85 @ Exercise Write the Matlab commands and their ouput for the {following.(use ”’ notation for taking power) @)2*10" ‘b) 0.003+0.444j )3*t0's4*10") Operators Expressions use fhmilaraithmetie operators and precegence rules, = Addition = Subtraction Exercise * Multiplication Write the Matlab commands and their ouput for the te following. 1 Division ape Power (Exponential) >> 16/2+(13°6)/3 >> (344i)! + Complex conjugate transpose >> 544-3" copyright © by IEE Student Branch, UET Lahore, This materi IIs exclusively forthe use of student of MATLAB Workshop 2012 organized by EEE WIE Afinity Group and IEEE Student Branch, University of Engineering & Technology, Lahore w pis wecnkebon 204, wall (Spit evaluation onter Matrices and Arrays vanes aaa ‘The most et explore tl snatr mantpuatin 1 MATL a pelieved at ines g 1 most enthusiastic way to explore th a The ratrits shown in adjacent plture This mae ty svn Bese glen proper. ve wd ena 1 irivealled 10 To emer this matrix, simp % al Window ve fuos rin stort moe midis ‘To enter a Mati, you only have to follow the followin sinyple rales Separate the cements oF non wih bbnnks or earn ate list of elements Wi I end of enc 10 ich ques > Usea semicolon ‘aro the ent ets, MATLAB displays the matrix yon just entered ae w32 3 s os 96 7 2B aol .ce by one before explaining sum, transpose, and iiagobal “These are the built in function in NAA TTB for anatele operation, Leis us ry them on their function The first statement to try is sum) MATLAB replies with ans of A. Each of the coluinns has the same sun, MMM ‘Yow have computed a row vector cont the magic sum, 34 >» Next we caleu! operators, ape apostrophe operator (ez, A) performs 2 complex conjugate transposi Kerman diagonal, ad also changes the sign of the imaginary component of any comy the matrix, 1s without affecting the sign of complex elements. For + Thedot-apostropl. operator (6.85 A), transpos: aoe a containing al rel elements, the two operators rtum te same rest «aining the sums of the column jate sums of rows. Fr his pmpose, we use “ranspose operator. MATLAB has two transpose a matrix about plex elernents of ‘iy the following command and wrt its output in the space provided \ hop 2081 spe BY TEEE SUTTER EPEC, OEY CONGTE, THE MTDC OT srqnitd by FEE WIE Arty Group and IEEE Student Branch, University of Engineering & Technology, Lahore IEEE oo : BEEP EE EEE EEE ERE PEE H et ebeei iL “hn nll tke the transpose of B to produce a column vector containing dhe row suns PEE “The same result can be produce by using the command >esum(A’) : valent £0 osu A cults the row sum of A’ and then takes the transpose of resultant max. (row vector equys re ‘The diag fiction gives a column vector containing diagonal elements of the Matrix. You can verify it below. usu tl cacncarneaemarane 2 {verte MATLAB? Watch hi ideo, see Demos or rend Gsting ated x] 5) ref ©) | Name = b> dag) fee a at er » He fas t i-diag samt The function fliplr, flios @ matrix from lejt ¢o right. Calculate B=flipIr{A) and verify this, The function ( diag (iptv) ) gives the antidiagonal of Matrix A, Copyrignt © by ett student Uraneh, UEI Lahore: this mate i ExCSMEN Tor We Use Or HUCEAT OT ATLAS Workshop 2013 organized by IEEE WIE Affinity Group and IEEE Student Branch, University of Engineering & Technology, Lahore IEEE aR Functions ae provides a large number of standard elementary mathematical functions, many more advanced mathematical functions, including Bessel and gamma fun including 2b, s9r exp, and si, tions: and matrix functions (YP For a list of more advanced mathe: help speefun help elmat Constant Functio! them in command window: values of useful constants. Ty (PINE Several special functions pro’ —4 a 3.14159265, F2204e-016 | precision, iv | Smallest flosting-powi | > 2751€-308 1 | number, Ei saaiwax | Largest fleating:poin’"1.79776#308 [number inf Infinity 1 Tr generaed by viding a nonzero value by 2er0, oF BY evaluating well ! 1s gene atheoatcalepressions that overflow, exteed ress Sions like 0/0 oF In-Inf that do not hi ienerated by trying to evaluate expres well defined mathematical values, [NaN | Nota-number ‘The function names are not reserved. Its possible to overwrite any of them with a new variable, such as stored with cps 1-6 ot that value in subsequent calculations. The original function can be res clear eps Elementary Mathematical Functions Fora list of the elementary mathematical functions, help etfun Some ofthe more useful and commonly used functions are given be Ow. Trigonometric f€ommand [Function ‘Example ‘e output here Cosine. cos (pi/ 4) Cosine of argument in degrees. cos (45) [Hyperbolic cosine. cosh(2) [Inverse cosine ~[acos(0.7071) rad 7 [Hnverse cosine, result ‘in degrees ‘acosd(0.7071) ceed acosh Inverse hyperbolic cosine acosh(3.7622) hypot Square root of sim of squares hypot G4) student Bran, UET Lahore, This materials elusively forthe use of student of MATLAB Workshap Copyright © by IEEE and IEEE Student Branch, University of Engineering & Technology, Lahore organized by IEEE WIE Affinity Group — ll ——_ IEEE aatiae Workshop 201° Exercise Write Matlab commands to find output ofthe fot a folowing tr aan "9 trigonometric functions b) cosec(A/6) c}sec* (5) Exponenti Command | Function Exponential 2 Conte expe aearily expml(l) Notun gard : 5 | Common a 10) logarith; - eee =) T garth 1og10(100) | Bis gains nd Wise Gog po e2(4)) Ei meniab ingame — = : : z pow2(aj=2" {Nabal logan ofa aber i T : = ari of eal if teallog @7183) { = © Oot of number greater than oF equal to zero realsqrt(i6)_ | sare Square root se] Sqt-16)_ z ve Uiiroot | Real ath root of eal mumben: nthroot(16.2) | Exercise te ouipet of the following : reais read nember eget) sow eqrtN6) and sqrt 3) ama aro Workshop 2011 Organized by IEEE WE Atinity Group and IEEE tusent Branch, Univesity ot Engineering & Teewnology, Lahore angie 7 car tconpena| “cies ehelp sign >ehelp mod pedo sign c the function to find the details rganitedby12€ WE Affi Group and IEEE Student Branch, airy of Engnesting& Técholoay, Lahore spectaltzed. Math function, {yo advance! nvtherteal fuels typo tent, 6) lern(6,9) perms | All possible permutations, perms perms(32) nchoosek | Al comblr vations of N elements taken Kata | nchoosek(5,3) time,nchoosek(n,) factorial | Factorial function Exercise ospetmns (1:5) sperms(4:6) sepermst(7,3,4,91) fora of more advanced matsx functions, type lp Ane, Fllowng some srnpatant fanetions ment s eros. | Generate a null matrix af order specified in the eros(2) _| Null Matrix of order 2 by 2 | argument Zeros(2,.2) | Null Mateix of order 2 by 3 | ones” |/Generates a ones matrix of order specifier 2 ones(a) | nes Matrixof order 3*3 argument to the function j | I Tdentity matrixe.g evel® }generates an entity | eye(2) = j Identity Matrix of order 2 and 2 by 3 matrix of order 3 respectively J eee Copyright © by IEEE Student Broneh, UET Lahore. This moteralls excluslvely for the use of student of MATLAB Workshop 2011 seemed by ECE WIE Anity Group and IEE Student ranch, Universy of Engineering & Technology Lahore eyel23) | MATLAB od IEEE 28 254 between Xi ang ay spaced points between Xd angst erg F100 nearly equally P27" space retuins x2, oo tes a row vector linspace | LINSPACE(X4, X2) generat 4x2. For N <2 jeon X3 ant LINSPACEDKE, 2, N) generates N points BENNY 1X2, pence mL ce 5 Fees and diag atriees and Diagonal m: aie Eraract lower tangular part -eiract upper triangular part. — ‘rie Extract upper tia ec airetion ner of ee —| |e aig ae wmel "Numberofement ips Ae direction. mikes rin upldown ore | ipa Flip matrix ie i lay matrix or-text ‘pw disp Disp! size Sizeofarray length Length of veer rndims Number af dimensions cesar. el ea aly aa ys are numerical sequal Tella exercise Jinspace(%,100) linspace(2,50) | fnsoace,202) Built-in vs M-files Function Some ofthe functions ke sqrt and sin, are built in. Built-in functions are part of the MATLAB Cre so they are very efficient, but the computational details are not readily accessible. ther function, lke gamma and sinh, are implemented in M-files. There are some differences between built-in functions and other functions, For example, for built-in functions, you cannot see the code. For other functions, you can See the code and even modify it if you want. * Sch UET Lahore This ‘moter is exclusively for the use of studen forkshop 201 *Y Group and IEEE Student Branch, Univers of Engineering ar Sot ee ae Technology, tahore ] . IEEE Sn on 201) was wrk moglelh) generates magle math afer cmat ler ky se Renae >a >> RIS) D> BER (5) 2A(2) 7808) RUN) ae >> BIR) RIG) ATE) AGI Working with Matrices Subscripts ‘Any element ofa mattix cen be accessed by A(i,j) where isthe numberof row ofthe ciement while jis the number of ts column...For example, A(2.3) isthe number in the secon! row and third column, For the magic square or magic matrix, write the output >f the following Copyright © by IEE Student Branch, UET Lahore. This mate‘lis exclusively forthe use of student of MATLAB Werkshop 201% organized by IEEE WIE Afnty Group and IEEE Student Barr Unversity of Engineering & Technology, Lahore w MATLAB Workshey 2, ho lements fn satan possible to refer tot oer ei singe substi 10 vat Vis) ante ay offering (othe valu oo stored in AQ) AG) AG) ACI) ai AQ) M6) A010) ACL) Following 6 en AQ) AM) AWD aa AG) AGS) AC) ACLS) : show how to refer to an element with a single subseript, >> omnes arms The Colon Operator sing)e subscript Double subscript The colon, &, is one ofthe most important MATLAB operators, It occurs in several different fOrms. The ery {210s a row veetor contnining the integers from 1 to 10: 12345678910 To obtain nomunitspasine. we e:m specify an inerement, for example 302310 results 024568100 Coton in Subseripts: ‘Subscript expressions involving colons refer to portions of a rnatrix: | % AL) isthe first kelements of the th colums of A, % BCG) rogers to all the elenicas injth column: 3. while > C(1,) gives the first row ot C lusively for aaah the Use of student of MATLAB Work! 'ngineering & Technology jana. IEEE ‘pn Manian v Explotn the ourputineach step: ais Generating Matrice MATLAB software provides four functions that generats basi matrices zeros ~Generates Null matrix of the specified order ‘ones ~Generates Unitary Matix of specified rand ~Generates uniformly distributed random element randn ~Generates normally distributed random elements the ouput ofthe fllowing eee eer erst) sor = 2reneilza) soe 10'randl) Ne a randelayt | oa randnls) >oMeia(uorrand(5)] bn or MATL AB sesslons, dag a ree angular ample, outside of cor examples " or reads text file 7 "sy bianks vos sac cf a bes eT at umber of line and an ea nie m ctf conaiing these four! ikdat reads the flle t directory. The statement Joad magi mole matrix text or binary eat in the curren ik, containing the ea! to MATLAB from many and creates a variable, Mae formats is to use the Import san easy way to read dsta i aa Mefiles Youcan creete your own latices using Miles, which are text fi the MATLAB Editor oF another text editor to create 2 file containing the 5 ‘ou would type at the MATLAB ommand line, Sava the file under a name that ends in .m. i, eate a fiein the current directory ramed magikm containing these five lines: 6.03.02.0 13.0 011.080 07.0120 5.014.010 ent les containing MATLAB code, ame statements 0 x raat file and creates a variable, A, containing zhe example matri A, 8 4 ix, Concatenation sul here iia. 88 616 se of Engineering gem rng ait OT ATLAS Wor aot IEEE etna Sows-ant Columns Jelete rows and columns from a mattix using j 7 sucan coe a. SS yatin(20°ran A) 2 pair of square bracke' Me pen to delete the second column of X, use pale you delete a single element from a matrix, the result is not 2 matiix anymore. So, expressions ike Mii2 resultin an error. However, using a single subs script deletes a single element, or sequence of elements, and reshapes the remaining elements into a row vector So poms) =l) poMt[2:2: Ms 10) = 0) Copyright © by HE Student Branch, UET Lahore. This materials exclusively for the use of studen: of MATLAB Workshop 2021 ‘tanited by IEEE WIE Affinity Group and IEEE Student Branch, University of Engineering & Technology, Lahore IEEE * More About Matrices and Arrays Linear Algebra ; Informally, the terms matrix and array are often isa two-dimensional numeric array that represents a lined? 5D perations defined on matrices are the subject of Inear algebra- used interchangeably. More precisely, a mo, sa linear transformation. The mathemati, Generate a Matrix A and 8 and write the output of the following >> >>ata’ >>A.*B (Element by Element Multiplication) >> A*B (Matrix Multiplication) The multiplication symbol, *, denotes the matrix multiplication involving inner products between rows and columns, While, .* gives element by element multiplication. Determinant of a matrix can be found as follow >od = det(A) d The reduced row echelon form of Ais R= rref(A) Copyright © by EEE Student Branch, UET Lahore, This materialise lusively forthe use o orariedy EE WE Any Group and EE student Branch Uniestver ogee ese of MATLAB Wershop 08 esity of Engineering & Technology, Lahore IEEE onal that auras when they ate taken away (Fon the world of near algobya, on ‘ame wwordimens 8, wvatriens bee eons jumneric arrays. Auithmetle operations on arrays are dona element by element: This ™ aiton and subtraction are Uhe Sanne for arrays ant mateees hen ahat muitiplieat¥® operations ave different, MATLAR Uses a dot, docimal point, as part of the notatlon fOr Srultipheative array operations. ee dhe list of OVEFALOTS includes a Agito gutraction + Glement-by-element multiplication gement-by-element division \ gement-by-element left division x flement-by-element power » unconjugated array transpose array operations are useful for building tables. Suppose nis th n=(0:9)3 (Transpose of row vector 0 to 9] Then ye [nn422.4n) uilds a table of squares and powers of 2: Te column vector The elementary math functions operate on arrays element by element. So format short 0.1:2)'; logs = [x 1og10(x] builds a table of logarithms. logs = copyright© by IEE student Branch, UET Lahore. This mater as exclusvey for te sec! oe pee Workshop 2011 ering & izchnology, Lahore enganized by REE WIE Affinity Group and IEEE Student Branch, University of Engines ae > rh MATAR Workshy mm ‘Scalar Expansion 24 Matrices and scalars can be combined in several different ways. For example, a scalar is subtracted from a matrix by subtracting it from each element, agic(4) >BSA-85 forms a matrix Be Whose sum is >esum(B) ans= With scalar expansion, MATLAB assigns a specified scalar to all indices in a range, For example, B(2:2,2:3) = 0 zeroes out a portion of B: The find Function The find function determines the indices of array exements that meet a given logical condition Inits simplest form, find returns a column vector of indices. |= FIND(X) returns the linear indices corres ponding to the nonzero entries of the array X. Xcat also be a logical expression. 1 = FIND(X,K) returns at most the first K indices corresponding to the nonzero entries of the array X. K must be 2 positive integer, but can be of any numeric type. For ecuniple, : 7 oo tonnes find) 1 find(A) returns a list of indices in Matrix A Correspcinding to non-; Cooyright © by IEEE Student Brane ome above example with Bseye(2,3), seythe it only return fst two indices corresponding to nonzero elements of the matrix B ' faiprine" K find(isprime(A)) picks out the locations, using one-dimensional indexing, of the primes in the magic square and transpose is taken to get a row vector. Copyritht © by IEE Student Branch, UET Lahore. This material exclusively forthe use of student of MATLAB Workshop 2011 corganited by IEE WIE Afnity Group and IE Student Branch, University f Enginrering& Techno'ny, Lahore MATLAB Prog ramming file called an M-file (named af « ‘When you its m/file extension). There are two types ef M-files that you can write: scripts and function 7 This section covers basic program development, déscribes how to write and call scripts and Tymetions, and shows Now £0 Pass Gifterent types of data in 2 function call. -ogramming basic write a MATLAB function or script, you seve It to @ program your program code using any text editor. This section focuses on using the er for this purpose. 3 program is to open an ed pe the word edit at the MAT creatin iting window. LAB command prompt. in creating name: edit drawPlot.m The first step ! -file,tY To create anew MATIC w To-edit an existing Mile type edit followed by the file pens a new window for entering your program code. As you type in your Program, MATLAB OF y the line numbers in the left column. MATLAB keeps trac Progra It is usually a good idea to save your program pericdically while you are in the development process, To do this, click File > ‘save in the Editor/Debugger. Enter a filename with @.m extension in the Save file as dialog box that appears and click OK, Itis customary ‘and less confusing if you give the M-fi the first function in the M-f'e. Running the Program rogram, make sure that it Before trying to run your P MATLAB path defines those directories that you wan ivifiles, The path includes all the directories that contain fi ou use fo your own functions. should also include any directories that y k of Savi Je the same nameg 5 M-file is on the MATLAB path. The t MATLAB to know about when executing unctions provided with MATLAB. It M-Files language that enables you to write a series ides a full programming |: hem with a single command. You write The MATLAB software provi te tl of MATLAB statements into a file and then execu your program in an diary text file, giving the file a name of filename.m. The term you use for filename becomes the new command that MATLAB associates with the program. The file extension of .m makes this 2 MATLAB M-file. Copyright © by IEEE st ch, UET This materi ci f student ‘TLAB Workshop 20) Student Brant i i Vaadbneitone 1 Branch, UET Lahore. This material is exclusively for the use of student of MATLAB Wor a rgonited by IEEE WIE A/F Group and IEEE Student Branch, University of Engineering & Technology, Lahore | —__ fap) @iEEE al of M-Files : ‘can be scripts that simply execute a series of MATLAg in be also accept input arguments ang aa statements, or they Ca! ut put. yaa sets for automating a series of steps y 7 are usetul at «Ae rotacent input arguments return cupur sneer NY tes «store variables in a workspace thats shared with other seripts and with the MATLAB command line interface, (MATLAB function: « re useful for extending the MATLAB language for your application. « Can accept input arguments and return output arguments, « store variables in a workspace internal to the function, Wile Element) Function definition line | Defines the function name, and the number and dfanetions only) order of saput and output arytuiments H1 line ‘Aone line summary description of the program, displayed when you request help om an entive directory, ov when you use 100k? © Help text, A more detailed description of the program, displayed together with the H1 line when you request Nelp on a specific function evipt body | Program code that performs the actual computations and assigns values to any output arguments ‘Comments Tex Function or ¢ in the body of the programm that explains the internal workings of the program un jon Line The function definition line informs MATLAB tat the M-file contains a function, and specifies the argument calling sequence of the function. This line contains the function keyword and must always be the first line of a function Mele. function y = fact(x) function Name —e Function names must begin with a letter, may furetion nase contain any output arqurent alphanumeric characters or underscores, and ust, agnor bbe no longer than the maximum allowed length (returned by the furiction namelengthmay). Copyright© by IEE Student Branch, UET Lahore. This materials exclusively forthe use of student of MATLAB Workshop 2011, organized by IEEE WIE Affinity Group and IEEE Student Branch, Unversity of Engineering & Technalney, Lahore IEEE “mnxa wens. fthe function name wi, 11 The name of the text file that contains @ MATLAB fc nction conse ard chafunction defn sion m appended. for example, average!” Ifthe fl oy, the exte that defines 2 FUNCTION nary, line name are different, the . t, file internal function) name is ig ced. Thus, f average i evereee Raa eae soar yout wake te unctin BY PINE TT ing does NOt RAVE obey, fied on the function oF avoid confusion. . Note While the function name speci incon same as the filename, it is best to Us® the same nam el ument list in square brac| ifthe function has niiple ouput values enCOSe the out ore ees Pach, Input arguments, if present, are ‘enclosed in parent 1e5es FO" 7 ale it ot cra: to separate multiple input oF OUtPUt argur: junction named sphere Here is the declaration for ° e(thete, phi, rho) function [x ¥, 2] = eh" ithere i al leave the output blank function printresults() or use empty square brackets function [] = printresultstx) The variables that you pass 10 the function do not! function definition line. ‘ jents. hat has three inputs and three outpu ed to have the same name as those in the e Function or. Bo The function body contains all the MATLAB cod values to output arguments. The statements in th input/output, calculations assignments, comments, and blank lines, for example, the body of the average function con:ains a number of simple programming statements: [m,n] = size(x); if ({(m == 1) || (n == 1)} || (m == 1 8& n == 1)) % Flow control error('Input must ke. vector'| % Error message display end = sum(x)/length(x); % Computation and assignment Creating a Simple M-File You create Miles using a tex 3 text editor. MATLAB provi i ides a built-in editor, b ; but you can use any text editor you like. Once you h; ren and he Mefi N run the program you have write i ee aoe ie sen and saved the M-file, you can run the prograi as or command, The process looks like this le that performs computations and assigns he function body can consist of function calls 2 Cal the Bete commani li TS Nate © = nyfilera,ey B.2r08 MATLAB Commands Program Control Statements Conditional Control — if, switch To make the selection based on whether a condition is true or false, use theif statement (which may include else or elseif).To select from a number of possibl ie options depending on the value of an expression, use the switch and.case statements . You cannot define nested functions within a conditional control block. Nasted functions must always be defined at the top level of a function. if, else, and elseif if evaluates a logical expression and executes a group of statements based on the value of the expression. In its simplest form, its syntax is if logical_expression statements end Copyright© by EE Student Branch, UET Lahore, This mater excels the se fase peta Workshop 2011 organized by IEEE WIE Affinity Group and IEEE Student Branch, Unversity of Engineering & Technology, Lahore ee ® IEEE |ATLAB Works, MATLAS Weta, i For example, if rem(a, 2) disp('a is even’) b=a/2; end jonalize the if statement: ‘The else and elseif statements further con ifn-< 0% Fn negative, display error message. disp(‘Input must be positive’); elseif rem(n,2) == 0% If n positive and even, divide by 2. Aza/2; else ' ‘A= (n#1)/2; 3 fn positive and odd, increment ane divide. End switch, case, and other switch executes certain statements based on the value of a variable or expression, Its basic form is switch expression (scalar or string) case valued statements % Executes if expression is valued case value2 Statements % Executes if expression is volue? otherwise statements % Executes if expression does not % match any case End Note For C programmers, unlike the C” That is, if the first case statement is true, other case statements do not execute. Therefore, break statements are not used. the MATLAB switch does not “fall through You can nest multiple for loop: for m= 1:5 Copyright © by IEEE Student Branch, UET Lore. This materials etlusvely forthe ue of student of MATLAB Werkshop 20, ‘organed by IEE WIE Af in Group av FE Student ranch, Univers of Engineering & Techroloy,Lahoce han) = a/em += 3h end \ end while @ The while loop executes a statement or group of statements re;antedly 9» long a8 1 controling expression fs true (1), Its syntax Is ‘while expression statements end For example, this while loop finds the first integer n for which nl (n factorial) Is a 100-digtt number. n=l; while prod(1:n) < 1e100 ‘ nent]; end Exit a while loop at any time using the break statement, i M-File Scripts Scripts are the simplest kind of M-file because they have no Input or output arguments, They are useful for automating series of MATLAB commands, such as computations that you have to perform repeatedly from the command line, ple Script Example These statements calculate rho for several trigonometric functions of theta, then create a series of polar plots: % An Mile script to produce % Comment lines % "flower petal" plots theta = -pi:0.01:pi; % Computations rho(1,;)=2* sin(S * theta) .* 2; rho(2,:) = cos(10 * theta) .* 3; tho(3,;) = sin{theta) . 2; tho(4,:) =5 * cos(3.5 * theta) .* 3; for k= 1:4 Polar(theta, rho(k,:)) % Graphics output Copyright © by IEEE Student Branch, UET Lahore. This materiel is ‘exclusively for the use ul sudent o of MATLAB Workshop 2011, teanited by IEEE WIE Affinity Group and IEEE Student Branch, University of Engineering & Techno ‘oty, Lahore roll MATAR Wark, pause end «file is now a MATLAB scripy [s.m, Thi ‘ ie ‘ments in the script. mands In an M-flle called pe' {25 the stater B command line execut2 plot ther lot, press Enter or Return to MOVE to the next pl © are ng ale ereates the variables needs In the MATLAB workspae, ve variables (i, theta, and rho) remain In To se id prompt. Try entering these com Typing petals at the MATLA After the script displays a pl input or output arguments; P When execution completes, | listing of them, enter whos at the comman Simple Function Example he average of the elements in a vect, The average function i a simple M-file that calculates tl function y = average(x) % AVERAGE Mean of vector elements. % AVERAGE(X), where X is a vector, is the mean of vector '% elements. Nonvector input results in an error. [m,n] = size(x); if (~((m == 4) | (n == 1) | (m error{'Input must be a vector') end y= sum(x)/length(x); % Actual computation Try entering these commands in an M-file called average.m. The average function single input argument and veturns a single output argument. a To call the average function, enter , 21:9) average(z) ans = 50 of MAT 2 BB Techy ATLAS Workshop! 4 sun 2 loop to plot three sine curves, pore 228 plot ix, sin(c*x)) echo oft < echo on pold off e pure title on the figure. titie(*Severai Sine Curves") pause opright © by I&€ student Branch, UET Lahore. This materials exclusively forthe use of student of MATLAB Workshop 20: forkshop 2011 cepaited by IEEE WE afirity Group and IEEE Student Bronc, University af Engineering & Technology, Lahore IEEE MATLAB Worksh, ort DATA Import and EXP + it into the MATL lipboard, import It Inte Towork with data you have stored in disk files or 07 the ipo a ems Workspace, The easiest way to import data is to use the Imp : the Ma ariables to use in 'nerface. The Import \. card helps you find a file and define the v Tuy erface, The Import \. ard helps Workspace, ds ing methods: To start the import Wizard, use une of the following meth * Select File > Import Data. * Call uiimport. * Double-click a file name the Current Folder browser. ting different file formats: if ts: MATLAB includes a set of functions to import specific file forma * MATAiles * Text (ASCII) data * Spreadsheets * Scientific data * Images * Audio and video To find a specific fle on the MATLAB search Path, Use the ‘which’ function. If the file isnot in the current flder, Include the fullor partial path vith the file name in calls to import function myfile.mat ich\'myfile. mat’); load(fullname); For example, to locate and load fullname = wi S automatically, Import Data dialog box. in the tabs above the display pane, which the Import Wizard has sorte » The variable nay * textdata — Matrix containing all imported tit data, Empty elements are set to", + data — Matrix containing all imp orted numeric data, Empty elements are set to NaN. > Ifthe imported file or clipboard contaias only numeric or only text data, then the Import Wizard assigns all of the data to just one variable, For data imported from a text file, the name of the variable is the same as the filename, minus the file extension, Jusivey for the use cf “tudent of VARTLAB Workshop 2012 juli exclusively for abereniis mate ing & Techne!»ry, Lahore Copyright © by IEEE Student Branch, UET Lahore. T ing & Tech of Engineer judent Brane!, University organized by IEEE WIE Affinity Group and IEEE Studer your WOTKSPRCE, use th disk to i Sag le on your ol Je operation lif yoy g, mrkspace in 2 sin it mat): binary or ASCII file le rom the works ds from file ma To import variables from 2 II varia You can load a} ; in MATLAB software [03 laden eu sped toad just those variables that or loa var bles that toad filename vor nae wr plead those vari match, the veriable Shey ample, the following command loads a Varig J) For ex: ” filename, the Use te wldard character ("a Pe ‘pattern. (This works for Mi-files only] that star with ‘ste from ile strinfommat load strinfo str ‘When you import data into the MATLAB workspace, it overwrites any existing varigy workspace with the same name, So wiewing MAT file contents:- To see what variables are stored in a MAT-file befcre act ‘workspace, use ‘whos -file filename’. This com; ‘lass of all variables in the specified MAT-file tually loading the file into your mand returns the name, dimensions, size, nd Sele cclina a range of numeric data:- Consider az 7.2000 85000 6.2000 5.6000 5.4000 9.2000 g, To read the first two ere Solurnns from A.d; partial = dimread (gat +» ‘AL..B2") ‘ SP Ob EE Studer, PONTE eae aT Ti at Fay erlalisexclusi ne PardlSe Student Branch, mye tBu ude ot aariag oe Workshop 2 RY Of Engineering Technology, Lahore SIEEE We a_partial = 7.2000 8,5000 5.4000 9.2000 sy) Aumerie Dato: : Toimportan ASCII data file with fields that contain nonnumeric characters, use ‘textsean Method is ' Open a file: Use ‘fopen’ to open a file for reading, pescribe your file: The ‘textscan’ function is flexible, but requires that you specify more information about YOUr file, Describe each field using format specifiers, such as '%s' for a string, '%éd' for an integer, OF * for a floating-point number. Close the file:- ! Use ‘felose’ to close a file, EXAMPLE: fid = fopen('mydata.dat’); mydata = textscan(fid, "%s %s 6F %d %s'); fclose(fid}; READING DATA IN A FORMATTED PATTERN To import text files that importdata and textscan cannot read, consider using ‘fscanf’, The {scent function requires that you describe the format of your file, but includes many options for this format description. Open a fil Use ‘fopen’ to open a file for reading. Describe your file: apyrght © by EEE Student ranch, UT Lahore. This materi exclushel forthe ue ol student of WATLAB Workshop 2011 cvganited by EEE WIE affinity Group and IEE Student Branc, Univers of Enneering& Technology, Lahore a ‘! fora string," for 29 Integer, ory s ol wo D crive each field using format specifiers, such as scribe e2 for a floating-point nu he’ ji toclose a file Use ‘felose ‘fv wiubes uf velites i oe are tion until t cannot match the description toy, = i t descrip i, fscanf reapplies your format ea = Eon “eaches the end of the file Optionally, specify the number of va hat data, ort {doesnot attempt to read the entire file, san file = fscanf(fid, '%F,, [rows, cols])'sj rows and columns must be specified. e wher ee | eee = Fase Fils arrays with numeric values injcolumn order. To make the output array mate, the orientation of numeric data ina file, transpose the.array. EXPORTING DATA Save Function: To export workspace variables to a binary or ASCII file, use the save function. You can save al Variables from the workspace in a single operation (if you omit the filename, MATLAB uses the name matlab.mat) save filename oF save just those variables that you specify: save filename var ver2 ... varN Use the wildcard character (*) in the variable name to save those variables that match a specific pattern, For example, the following command saves all variables that start with ‘str’: save strinfo str* copy pent Ob EE Sten: ranch UET Lahore, This mate se Orteced by ee We atin ‘lusively for the use of student of MATLAB Workshop 2014 ' Group and IEEE Student Branch, University of Engineering & Technology, Lahore ps fete amine what has been Wren othe MAT. e 0 us compresses the data that you s:ve to a MATefile, Data compression can save ‘ ate yer + mount of storage space when ycu ar sores or workin 2 working with o ge files O° ala) compression is optional, however, and you can disable it either for an ind function © _work. 032 she save -n, of forall of your MATLAB sessions. Use the -v6 option with t! ression on a per-command basis: save filename -v6 persti aur off comp! _ opting a Numeric Array to an ASCI' File Using save:- rt the array A, where A=[1234;5678]; span ASCII data file, use the save function 2s follows: save my_data.out A -ASCII To exp0' sorting a Numeric Array to an ASCII File using save function: For example, to export the array A, A2[1234;5678h to 2n ASCII data file that uses semicolons asa delimit ms), er(characters between the data ite use this command: dlmwrite('my_data.out’,A, " “NOTE: By default, dimwrite uses a comma “as a delimiter. You,can specifya spa character as a delimiter. To specify no delimiter, use empty quotation m ce ("Jor other jarks ('"). ving to Text Date Files with Low-Level 1/0:- To create other text files, including combinatiins of numeric and character data, ronrectangular output fies, or files with non-ASCII encoding schemes, use the low-level ‘fprint?” function. och © by EE Student Branch, UET thor. Thismaterils exhale forthe v8 of student of MATLAB Workshop 2011 ieee student Branch, University of Engineering & Technology, Lahore organi by IEEE VIE Afinity Group 2nd OPK atid workshop 2011 IEEE For example: % open a file for writing iH ; fid = fopen(‘exptable.txt' (where ‘W is for writing) blank line 6 print a title, followed by * fprintf(fid, 'Fxpone s6close the file ntial Function\n\n'); fclose(fid); SASHES See Ee ese rece cE : NOTE: : To changaithe type opfite access, USE the: By default, Fopen’ opens files with read access. permission string in the call to ‘fopen’. Possible permis * for reading. + w for writing, discarding any existing contents of tl © a for appending to the end of an existing file. ion strings include: Copyright © by IEEE Student Branch, VE1 cunore. Ti |, VET Luinore, This material is eclusivey for the for the use of student of MATLAB W¢ Orksho, organized by IEEE WIE Affinity Group and IEEE Student 8: i nt Branch, University of Engineering & Technology, Lahore P2013 Open any M-file (e.g. publisha, m) frot ‘ fle. sample code is shown bere or” WOTk folder in MATLAB or you may create your own M- ‘low in figure 1: clear sll > for (ie1:10) Figure a es a - end: - tprinet (x: cls2tpit [ - vizsin(ea); = plot (tt, v1) To publish this file, you need to first divide it into portions called “cells” by inserting cell breaks with the help of double percent marker (26) as shown in the figure 2 below: copyright © by IEEE student Branch, UET Lahore. This materials excslvey forthe use af student of MATLAB Workshop 2012 organizes by IEEE WIE Affinity Group and IEEE Student Branch, Univers of Engineering & Technology, Lahore IEEE MATLARWovtshy oI 204, g- tor (i=2F10) ae suede ac 18 5 ii- gpeineg('xted ay XD ae _ cregepit (020-0224) 7 yiesin (tt)? = prot(ed, Val le Cell Mode to turn on the cell toolbar. Now enable cell mode by selecting Cell > Enab settings, go to File > Publish to HTML. This wit To publish this file to html document with default s¢ Il the generated results. If there are any plot commands execute your M-code and you can see al de, then the resulting weveforms willbe plotted along with cells and published to an ile’ publish1.html, along with other supporting in your ¢t ing publish.m. The output file consists of HTML document. MATLAB stores the output fi of the folder con*aini output files in an htm! subfolder and the ommand window output. title, a list of contents, code, plots (if any) he list given by: File > Publish You can publish the M-file to other formats too by selecting from t! to >. Other formats may be doc, xml, latex, pdf, ppt etc. You can add more descriptive text and formats to your output document. For example: Cell Titles: You can add title for each cell by writing the title after the double percent marker (36%). The first title appears as the title of html page and the other titles appear as headings subsections, A contents list having section headings is automatically created at the beginning the document. Click on the links in the list to access them directly without scrolling on the pase Copyright © by IEEE Student Branch, VET Lahore. This materials ecclusively forthe use of student of MATLAB Workshop 2014 Panay by IEE WIE Ainty Group and EE Student ranch, Univrsy of Engineering @ Techelogy, Lahore ey OW aataAb Workshop 2021 pmunents: in order to give some description in the code, "comments can also be wited i it " also be wed in the M-code with yg sign at the beginning of comment tine, Ani yd i i converted Into the body text of the uheia scription given in file within the comments is sument. Figure 3 contains titles and comments. {SITE RR Hie Edt Text Col Took Debug Destap Window pe thBon (Slay a @ O08 1B) ~ [19 J+] yy Avsigning values to vi "Le and plotting warezomm ow Clearing the oi a> ele 5+ clear all wand seinen 29% For Loop 6 « For loop iterates 10 times and assigns the valu 9 v vo variable © to- for (41:20) te RCE i> ends 3 i 88 Printing variable values 18 § printf prints x. Here '\n! 4s Line feed. 16° tpeinet('xead \nt, x) ” 300s Potting sine wave is sin{) as standard Libcary function co plot sine vave,| 20> eanztpir [0:0.01:1]7 ae vissin(tt) 2- plow(td, vi) Font. Kormat: h You can format your text by inserting special markup text. For example you can add basic font format options like mono-spaced and bold words, You can write mono-spaced text by writing it in between bars (|Word]|). Any word can be converted to bold text by writing it in between the asterisks (*word*), Bullets can be inserted using Asterisk sign at the beginning of the line. An Copyright © by ee Student Branch, UET Lahore, Ths materi is exclusively for the use of student of MATLAB Workshop 2012 ‘rganited by IEEE WIE Affinity Group and IEEE Student Branck, University of Engineering & Technology, Lahore Ww MAT-AB Workshop 29, markups can alternatiy,, equation can be written using the standard LaTex markup ($$). These Veh, be inserted through the context Menu, This menu appears when you right click on an Mary line of the M-code. Fo, matting is shown in figure 4, Preferences: There ate 2 number of Preferences thet you can est with publishing, For example whether or not to show the code in output, Specify the default output format (html or else). Styleshee, specifies the Extensible Stylesheet Language (xsi) ‘ile that you want MATLAB to Use when yoy specify a format of ‘html, “xm, or ‘latex’, ImageFormat Specifies the file type for images that hing M-files, eva MATLAB runs the code that iis publishing, MATLAB produces when pubis; ‘Code Logical value that specifies whethe, You can do this all by selecting File 5 Preferences » Editor/Debugger > Publishing >. 7 8% For loop 8 & For loop: 3 10 + iterates 10 times ang 41% * assigns the values to variable x, Ws tor (i=1:10) 13- x(i)=i: Figure 4 wa- end; 45 16 °% Printing variable values : 170s [tprinet| p ones X. Here '\n! is s1ine seeds, 18> tpeinet('x=sa \nt, x) 19 20% Plotting sine wave 214 sin() is standard Library tuncticu to plot sine wave ay 2 $89 = sin (x) 46 t1*2*pit [0:0.01; 1); 25- vissinitay; 26- plot (ei, vi) You can also publish the M-file usin ‘an add different publishing settin window, 8 the publish command in MATLAB command window, yoy 8s for different files by specifying them in the commang Pvt @ by ee stu vy forkshoy ‘dent Branch, UET Lahore. This materials exclusively forthe use of student of MATLAB Workshop 2033 Bites by EE ip : inering & Technology, Lahore Alfirity Grovo and i€ce student Branch, University of Engineering & Technology, y~ IEEE ‘of syntax publish (file : publish (file, format’ publish (file, options) publish('file’,..) my. doc vy publish (file'} simply publishes the file i: described earlier. ¥ publish (file’, format’) publishes filem to an output file specified by the format field. ¥ publish ('fle', options) publishes file. using the structure option: ¥ oe ee Teturns the output resulting from publishing file.m to my_doe, format may be doc (MS word document), htril, ppt, pdf etc. viewing the published file: after executing publish command, in order to vie’ the published file in the web browser, YOU can get this file from the html folder in th current directory window or simply write this command in command window: : web (‘htmi/file.htm!") A glimpse of the published html output file is: copyright© by IEEE Student Branch, UET lahore, Tis mater excuse forthe use of tudent of MATLAB Workshop 2011, srenied by EEE WIE afiy Group on EE Student Banc Unies of Engineering & Technology, lahore Assigning values to variable and plotting waveror" Contents + Clessop ths eqmmand wind + Fouinen + Boing variable vabies Gearing the commant window Figure 5 8 fear all For loop For loop: + iterates 10 times and + assigns the values to variable x ser (se z= ena: 210) Printing variable values ‘Speinvz prints x. Here Wiis line feed 1. Open publishi.m, publish it to HTML, and then view the published document in web browser. 2. Open publishi.m, publish it to Microsoft Word format by using a structure, and thet view the published document in Microsoft word by typing a command in commant window. Hint: Structure in command window can be defined as: options_doc_nocode.format="doc’ 1 options _doc_nocode.showCode=false etc. 3. Open publishi.m, create a structure to specify the input values, publish i then view the published document in MATLAB web browser, Publish it to HTML, a ce by eee Student rane. UET Lahore Tht materials éiustely forthe use, gee WE Any Group and EEE Student Branch Uni erty of Eagner Copyright organized by of student of MaTLag Workshop 20! 1B Technology, Lahore —————— a IEEE Plottin AS Workshop 2021 9 Graphs & 3p Visuatizati ae ualization The basic features of H of MATLAB include the commands («ot data visualization (i.e. giotting) By typing help plot yo dimensional plotti YOU can see the various capabif, tw it. Ne iuntates command for strated below, Wixand y are two veet: ‘ors of the same length then plot(x,y) plots x versus y. sxample i To obtain the graph of y= omponents equall Braph of y= cos(x) from -mto m, we can first define the h « y seacel nineteen fe vector x wit with increment, say 0.01. 0.01. We placed a semicolon at the end of the input line to avoid \ seeing the (long) output. Note that ad the smallest the increment, the / “smoother” the curve will be, Next, we define the vector y » yecos(x); ‘And we ask for the plot »plotixy) A Anew window willopeninwich | the graph (as seen below) will appear. he axis on @.graph and if applicable indicate what each axis It is good practice to label t he xlabel and ylabel commands. represents. This can be done with ti » xlabell's') » ylabell'y=cos(x)’) \d enclosed with n single quotes, we type the text that we wish to. Inside parentheses, 2” ly. We could even put a title on top using be displayed along the x and y ax!5, respectivel is exclusively for the use of student of MATLAB Workshop 2021, p ertatore. This materl University of Engineering & Technolgy, Lahore ieee student Branch, Copyright © by Ieee Student Br ‘Group andl cvganized by IEE WIE ATINIY 4 ANUAU Why "Op iy IEEE » title('Graph af cosine trom nto) These commands can be invoked even after eo] the plot window has oak been opened and ot MATLAB will make all the necessary sl adjustments to the Ro display. “yr / \ yh \ dl f % 7 —— Various line types, plot symbols and colors can be used, If these are not specified (as in the case above) given in the table below. ) MATLAB will assign (and cyele through) the default ones as Yellow. point magenta oo eircle c cyan x x-mark | r red + plus i e green - solid b blue . star He w white : dotted k black - dashdot : - dashed Copyright © by IEE Student Branch, ULT Lahore. 7 organized by IEEE WIE Affirty Grown 2 1 of MATLAB Werksho? 2 | | 3 «clusively for the use of student Ing & Technology, Lahore is mateo is fversty of Engineer! and IEEE Student Branch, Unt IEEE Oe on We could get a dashed line instead of 4 solid one by typing Bpear on the same graph. I for example we define another vector and get both graphs on the same axis, distinguished by their line type, using 5 z= sin(x); » plotiy,y,'r~!%,2,'be') The resulting graph can be seen below, with the red dashed line rey presenting y = cos(x) and the blue dotted line representing z = sin(x). itis co create 2 legend to When multiple curves appear an the same axis, itis on idea 4 actly this. lebel and distinguish them. The command legend does exactly he ute of student of MATLAB Workshop 2011. is materilis exclusively fort ne ach oovight © by IEE student Branch, UE Lahore. This materi exc ee roel ch, University of Engin Ortantedby IEE WIE affinity Group and IEEE Student Branct, UI Soe Te Eee Pee eter eeeeeee eee > A legend('cos(x)','sin(x)') Je quotes aS input to this command, sapiens the vt ne two curves 5° since in the ploy he same here. The text that appears within sin ering of t must do # legend labels, We must be consistent command we asked for cosine tobe Plot sat it subplot You can show a number of Plots inthe same figure window with the SUPPIO function, The statement and selects the pth set for the curren » subplot(m, ", P) II sets of 85, r example, ndow into men smal ‘rom the [et of the top row). Fo! divides the figure wil ered by row plot (num own. produce the four plots shi the following statements » [x y= meshgrio-30.3:3); 22K." explerA2- ¥"2): » subplot(2,2,1) » mesh(z),title('subplot(2,2,4)) » subplot(2,2,2) » mesh) » view(-37.5,70),title('subploi(? 2,2)') » subplot(2,2,3) » mesh(z) » view(37.5,-10), titie('‘subpiv:,2,2,3)') » subplot(2,2,4) » mesh(z) Copyright © by IEEE Student Branch, UE oreenined by EEE noah UET La by EEE We Afi ere, This material se ty Group and IEEE Stude eee eee Branch, Univesity of Engines ne user of MATLA ngineerin 1 Worksho ing & Techno logy, Lahore oe on IEEE » view(0,0),title('subplot(2,2,4)') MATLAB W subplot (2,2, 2 You can observe the rest plots by yourself. Another feature that can be used with plot is the command grid, which places grid lines to the current axis. At any point during a MATLAB session, you can obtain a hard copy of the current plot by either issuing the command print at the MATLAB prompt, or by using the command menus on the plot window. In addition, MATLAB plots can by copied and pasted (as pictures) in any word processor (such as Microsoft Word). 3-D plots

You might also like