You are on page 1of 527
The Finite Element Mlethot using MATLAB Young UW. won Hyochoong Bang CRC Press Boca Raton 14 igton, D.C. CRC MECHANICAL ENGINEERING SERIES Edited by Frank A. Kulacki, University of Minnesota Published Entropy Generation Minimization Adrian Sajaan. Duke University The Finite Element Method Using MATLAB Young W. Kwon. Naval Pastaraduate School Hyochoang Bang, Korea Aerospace Rasearch Insthiute To be Published Fundamentals of Environmenta! Discharge Modeling Lorin A, Davis, Crogan Stato University Mechanics ot Composite Materials Autar K. Kaw, University of South Florida, Norlinear Analysis of Structures M. Sathyamoarthy, Clarkson University Mechanics of Solids and Shots Gerald Wempter, Georgia Institute of Technology Viscoelastic Sottas Roderic Lakes, University of lowa LIMITED WARRANTY CRC Press warants the ptysical disketto(s) enclosed herein to be fee of defects in uateriak ad workmanship for a period of thirty days from the date of purchase. if within the wartanty period CRC Press receives writen nolification of éefects in materials oc workmanship, and sein notilicelion is destined by ORC Pres he come, CRE Fress Wl replace me detective atsectet ‘The ealis and caddusive lability and remedy for becac of dis Linsiled Waray shall Tinted wocpiacement of defective disketie(s} and shall wot nul ur extend to any claien for or right cover any ober damages, achdieg but nottimited 10, lost of prof, data, af use ofthe cofewave, ot special, incidanal, of csnsquential damages or other Amilar claims, even if CRC Press fas been specifically advised of the possibilty af ach damages Fr wo even wil the liabiy of CRC Press for any damages to you or any ofter person ever exceed the lower sugested ist pie 9 cual pfite paid for the software, regardless of any form of the claim. ‘CRC Press specifically disclaine all other weerantics, expeess ce implied, icuding but oi inited 0, any iplisd ‘warranty of metchantabiity 07 fimness for a particular purpose. Specifically, CRC Press makes no presestation o¢ ‘warranty thal the softwave is it for any particular purpose and any ixaplied warranty of mercuabillys bie Te CLIMY-day eoreTion ef the Liraied Warranty covering the physlcel askees) ony (aN Noche SCO) sd otherwise eapressty and specifically disclaimed, ‘Since noe Mules de nol allow the exclusion of invidentaf or consequent! dang on implied warranty last tonsa af the akove may not apply v0 you srthe lization on howe lag. DISCLAIMER OF WARRANTY AND LIMITS OF LIABILITY: Thc ator ofthis book hae ued her best efforts in preparing this material These efforts include the development, rescarch, and testing ofthe theories and programs to determine cheir effectiveness. Neitacr the author(s) nor the putliser make warantes of any kind, express or implicd, with regard to trese programs or the documentation conned i tis book, inculing wont limitation warrants of merchan‘ability oF tiness fora particular purpose. Ne lig Is arcpedin any event for any damages, tncluding incidental ur oonseyuentil Uareages. 109 profls, so of Ws Uae 9 EO MEET, OF otherwise in connection with of arising ot of the furnishing, peformance, o sof the programs in this book, Libcary of Congress Cataloging-In-Publleatien Data Kwon, Young W. The finite clerient method using MATLAB / by Yeang W. Koon and Hyocioong Sane, B. Ga — (The mechanical engincering series) Includes bibliographical references and index, IEDN 0-0493-7652-0 (alls. pepo) 1, Finite clement method—Tiata proesssing, 2, MATLAB — Bang, Hyockoone, TE Tithe IE Series: Advanced topics in mechanical enginesting series. TAMTFSKSS 1995 624.1 70285832090 96-1901 cp ‘This book contains information obtained from anthentc and highly reganled smrees. Reprint malta acted ‘with permission, and sources are indicated. & wie varcty ofreferences are ied, Reacomoblefiptshave been made to publish reticbte deta and information, but the author(s) and the publisher carnot asm respeulty fr Lae saldity of afl materials or for the consequences of their eae ‘Neither this book nor my part muy be reproduced or tansmilted in any for tr by any means, clcroe ot mechanical, inchuding photocopying, miczofilming, and recording, or by any infornatonsiomye ore system, without prior permission in writing from the publisher. ‘The consent of CRC Press LLC does aol extend to copying for general dveibution, for promotion, for erating new works, or for resale. Spesific pecmission must be obtained in writing fem CRC Press LLC for such copying, Disect al inquiries «9 CRC Press LLC, 2000 Comorate Bivd. N.W., Boca Reto, Horia 3431 © 1997 by CRC Pros LLC No elim tn original 18 Couersent work: Inreenational Standaid Book Number 0-8493-9653-0 Library of Congress Card Number 96-9091 Printed in the United Sites of America 34567890 Printed on scid-free paper TABLE OF CONTENTS CHAPTER 1. INTRODUCTION TO MATLAB La 2 13 4 15 La LT 18 19 1.10 LAL 1.12 113 au Lib Finite Elernent Method Overview of the Book About MATLAB Vector and Matrix Manipulations Matrix Functions Data Analysis Funccions Tools for Palynomials Making Complex Numbers Nonlinear Algebraic Equations Solving Differential Equations Loop and Logical Statement Writing Function Subroutines File Manipulation Boosie Input Output Functions Plotting Tools CHAPTER 2. APPROXIMATION TECHNIQUES a4 22 2.3 24 25 26 Ze Methods of Weighted Residual ‘Weak Formulation Piccawise Continuous Trial Function Gelerkin’s Finite Blenent Formulation Variational Method Rayleigh-Rita Method Rayleigh-Kite Finite Element Method Problems CHAPTER 3. FINITE ELEMENT PROGRAMMING BL 32 33 B34 35 CHAPTER 4. DIRECT APPROACH WITH SPRING SYSTEM 41 42 43 Overall Program Structure Input Data Assembly of Element Matrices and Vectors Application of Constraints Example Programs Prablems Linear Spring Axial Member Torsional Member u i 5 16 1 20 2 28 mu ay 34 35 a7 a2 4 a AG Bt 52 54 68 a a Wi 31 bL 1 44 Other Systems Problems CHAPTER 5. LAPLACE’S AND POISSON’S EQUATIONS 5. 5.2 5.3 54 55 5.6 5.7 58 59 5.1C DLL 5.12 Governing Equation Linear Triangular Element Bilinear Rectangular Elemert Boundary Integral ‘Transient Analysis Time Tategration Technique Axisymmetric Analysis ‘Phree-Dimensionel Analycio MATLAB Application to 2D Steady State Analysis MATLAB Application tu Axisymmetric Analysis MATLAB Application to Transient Analysis MATLAB Application to 3-D Steady State Analysis Problems CHAPTER 6, ISOPARAMETRIC ELEMENTS 61 6.2 63 6.4 6.5 6.6 One-Dimensional Elements Quadrilateral Elements ‘Triangular Elements Gauss Quadrature MATLAB Application to Gauss Quadrature MATLAB Application to Laplace Equation Problems CHAPTER. 7. TRUSS STRUCTURES a 7.2 73 TA 15 7.8 One-Dimensional Truss Plane Truss Space Teuse MATLAB Application to Static Analysis MATLAB Application to Eigenvalue Analysis MATLAB Application to Transient Analysis Problems CHAPTER 8. BEAM AND FRAME STRUCTURES at 8.2 8.4 84 8.5 Euler Bernoulli Boam Timoshenks Beam Ream Elemente With Only Displacement Degrees of Freedom Mixed Beam Element Hybrid Beam Element 7 80 83 86 90 92 96 38 jot 108 107 ng 124 M8 153 wT 160 168 170 1% 183 193 197 199 08 204 15 223 281 295 wz 45 zag 2a 83 187 1987 235 8.6 87 8.9 ata BLL 8.12 B18 B14 Composite Beams Two-Dimensional Frame Element ‘Three- Dimensional ¥ramne Element MATLAB Application to Static Analyeis MATLAR Application to Rigenvalna Analysis MATLAB Application to Transient Analysis MATLAB Application to Modal Analysis of Undarpped System MATLAB Application to Modal Analysis of Damped System MATLAB Application to Frequency Response Analysis Problens CHAPTER 9, ELASTICITY PROBLEM g1 2 9.9 94 9.5 2.6 97 a8 3.8 Plane Stress and Plane Strain Force Vector Bnergy Method Three-Dimensional Solid Axisymmetric Solid Dynamic Analysis MATLAB Application to 2-1) Stress Analysis MATLAB Application to Axisymmetric Analysis MATLAB Application to 3-D Stress Analysia Problems CHAPTER 10. PLATE STRUCTURES 04 10.2 10.3 10.4 10.5 10.6 10.7 Classical Plate Theory Classical Plate Bending Element Shear Deformable Plate Element Plate Element With Displacernent Degrees of Freedom Mixed Plate Element Hybrid Plate Element MATLAB Application Problems CHAPTER 11, CONTROL OF FLEXIBLE STRUCTURES dl 11.2 3 14 W5 116 17 11.8 11.9 11.10 Introduction Stability Theory Stability of Multiple Degrees of Freedom Systems “Analysis of 2 Second Order System State Space Form Description ‘Transfer Function Analysis Contro) Law Design for State Space Systems Linear Quadratic Regulator Mudal Contre for Secund Order Systems Dynamic Observer 28 9 264 265 0, 284 288 298 29 304 r BL 313 31a 318 320 82L 334 356 36L 364 368 373 378 308 303 304 398 401 408 Atz 427 438 451 307 361 393. PREFACE ‘The finite element method has become one of the must important ead useful engineering (uoly for engineers atid scieutisis. This ook prevents introductory and some advanced topics of the Finite Element Method (FEM). Finite element theories, formulations, and various example programs written in MATLAB! ate presented. The book is written a9 s textbook for upper level undergraduete and loner level greduate courses, as well as a reference book for engineera and scientists who want to write auick finite element analysis programs. Understanding basic program structures of the Finite Element Analysis (FEA) is an important past for better comprehension of the finite element methad, MATLAB ja especially convenient to writo and underatand finite clement analyes programe because a MATLAB program manipulates matrices and vectors with ease, Thess algebraic operations constitute major parts of the FEA program. In adiition, MATLAB has buili-in graphics features lo Lely ceaiers visuslize Ue wumucrical results in Wwo- and/or three-dimensional plots, Graphical presentation of aumericel data is important to interpret the finite element results. Because of thes: benefiie, many examples of fimte element analysis programs are provided in MATLAB, ‘The baok contains extensive illustrative examples of finite element analyses using MATLAB program for most problems discussed in the book. Subroutines (MATLAB functions) are provided in the appendix and a computer diskette which contains all the subroutines and example problems is also provided. Chapter 1 has a brief summary of usefal MATLAB commands which can be used in programming FEA. Readers may refer to MATLAR mammals for additional information, However, this chapter may be a good etait for readers who have no experince with MATLAB Subsequent chapters are presented in a logical order, Chapter 2 diseuseoe the weighted residual method which is used for the formplation of PEA in the remaining Clayvery, Tritially, cumtinuuue iia) fynctions ace used by oblaiu appruxiatale sululious using the weighted residual method. Next, piecewise continuout functions are selected to achieve approximate sohitions. ‘Then, FEM is introduced from the concept of piecewise continuous functions. Finally, classical variational formulations are compared with the weighted residual formulations Chapter 3 shows the basic program structure of FEA using ordinary differential equations for an one-dimensional aystern. MATLAB programs are provided to explain the programming. Both program input and output as well aa internal program structure are fully discussed. A direct, FEM approarh using simple mechasies i presented in Chapter 4. This chapter.presents the basic concept of FEM using an intuitive and physical approach ‘MATLAB is a registered tradomark of The MathWorks, Ine. For additional informationa, contact: Phe MathWorks, Tue 24 Prime Park Way Natick, MA 01760 Phone: (08) 647-100U, fax: (US) 647-7001 Finite element formulations for partiel differential oquations are presented in Chapter 5. ‘This chapter explains not only domain integration for computation of the finite element matrices but also boundary integration to compute column vectors Applications of Laplace's equation to two- and three-dimensional domains as well as an axially symmetric domain are presented for both stesdy-slale and transient problems. Chapter 6 shows concepts and programing of isoparametric finite elements Because a complex shape of domain with enrved bourdary can be eceily haedled using isoparametric finite clements, these clements ate very useful and common in FEA Both one-dimensional and two-dimensional isoparametric cements are presented. A numerical technique und ils programusiag concept are aluo divcusved. Ay 8 program example, Laplace’s equation is solved using isoparametric elements, Chapters 7 and 8 discuss truss and frame structures. Static, dynamic, and eigenvalue problema are solved. In addition, one-, two and three-dimensional structures are considered. As a result, coordinate transformation from local to global axes is explained. In particular, various formmlations fot the bea structure are compared; the relative advantages and disadvantages af each are cited. Modeling of laminated beams with embedded cracks is also discussed, Further, Chapter 8 presents the madal analysia and Fast. Fourier Transform Elasticity is studied in chapter 9. Plane stress/strain, axisymmetric and three dimensional problems are included. Both static and dynamic analyses ate presented. The finite clement formulatione are presented in terme of the weighted residual method. However, an energy method is also discussed for comparison. Plate bending is given in Chapter 10. Similar to beam formulations, diferent plate beading formulations are presented for comparison. Finaily, stractural control using FEM is presented in Chapter 11. This chapter ig intended to provide a broad understanding of the basic concepts of control law in conjunction with FEM. Due to limited space, only a few major control theories are presented. It is assumed that readers are already familiar with fundamentals of linear dynamic systems analysis. ‘This book contains more material than can be covered in a one-semester. Thus, materials may be selected depending on course objectives. For an introductory FEM course, Chapters 2 thrangh 9 ara recommended. Depending on the desired course contents, some sections may be deleted. We would like to thank individuals who have contributed to this book. ‘The authors would Ike to express out appreciation to Profeasor Alekandra Vinogtador for reviewing the manuscrips and providing us with many useful suggestions. We are also indebled to the staffs of CRC Press for their professional guidance ia the production of this book. Finally but not lastly the authors sincerely appreciate the lifelong support. and encouragement by their parents. Y.W. Kwon E. C, Bang CHAPTER. ONE INTRODUCTION TO MATLAB 1 Finite Element Method In order to analyze an engineering system, « mathematical model is developed to describe the system, While developing the mathematical 1odel, some assumptions are made far cimplifestion Finally, tha gaveming rathernalirsl aepraccinn is dovalepard to describe the behavior of the system. The mathematical expression usually consiste of differential equations and given conditions. These differential eyuativas axe usually very difflaus tu obtain solutions which explain the behavior of the given engineering system. With the advent of high perfor mance computers, it has become possible to solve such differential equations. Various numerical solution techniques have been developed and applied to solve numerous en- gineering problems in order to find their approximate solutions. Especially, the finite element methed has been one of the major numerical solution techniques. One of the major advanteges of the finite element method is that a general purpose computer program can be developed easily to analyze various kinds of problems. In particular, any compley ahape of peahlem damain with prescribed eonditiona can be handled with ease using the finite element method. ‘The finite element method requires division of the problem domain into many subdomains and cach subdomain is called a finite element, Therefore, the problem domain consists of many finite element patches. 1.2 Overview of the Book ‘This book is written as a textbuok for engineering students as well as a reference book for practicing engineers and researchers. The book consists of two parts: theory and program. ‘Therefore, each chapter has initial sections explaining fundamental theories and formulations of the finite element method, and subsequent sections showing examples of finite element programs written in the MATLAB program. The collection of MATLAB function files (i.e. m-files) used in the example programs is summarized in Appendix A and provided in a separate computer disc. 1 2 Tntraduction to MATLAB Chapter L A brief summary of some of MATLAB commands is provided in the following sections for readers who are nol familiar with ther, Those are the commands which may be used in finite element programs. Especially, the MATLAB commands for matrix operation and solution are most frequently ueed in the programs, For visxal- ination of the finite element solution, some plotting commands are alsa explained. 1,2 Abuut MATLAB MATLAB is an interactive software which has been used recently in various areas of ongincaring and ecientifie applications. Il is not a computer language in the normal, sense but it does most of the work of a computer language. Writing a computer code ja not a straightforward job; typically boring and time consuming for beginuers, One aliractive aspech of MATLAB iy that it ix celatively easy to Jean. Tk is wcitien ow an intuitive basis and it does not require in-deptin knowledge on operational principle of computer programming like compiling and linking in most of other programmsing languages. ‘This could be regarded as a disadvantage smec at prevents users from understanding the basic prineiple in computer prograraming. ‘The interective 1uade of MATLAB may redace computational speed in some applications. ‘The power of MATLAB is represented by the length and simplicity of the code, For example, one page of MATLAB code inay be equivalent to many pages of other compnter langnage source codes. Numerical calculation ix MATLAR uses collections of well written scicntific/mathematical subroutines such as LINPACK and EISPACK. MATLAB provides Graphical User Interface (GUI) as well as tatee-dimensional graphical animation. Ta general, MATLAB is a useful tool for vector and matrix manipuletions. Since the majority of the engincering systems are represented by marrix ard vector equations, we can relieve our workload to a significant extent by using MATLAB, ‘The finite element method is a well defined candidate for whick MATLAB can be very useful as a solution tool. Matrix and vector manipulations are eseential parta in the method. MATLAB provides help menu so that we can type felp command when we need help to figure out a command. The Aelp utility is quite convenient for both beginners and experts. 1.4 Vector and Matrix Manipulations Once we get into the MATLAB, we meet a prompt >> called MATLAB prompt. This prompt receives a user command and processes it providing the ouput on the next Hine. Let us try the following command to define a matrix. >> A= [L,3,552.7,8;0,5,9] ‘Then the ontput appears in the next line as shown below. Az ane: cnn Section 1.4 Vector and Matrix Manipulations 3 ‘Thus, a matrix is entered row by row, and ezch row is separated by the semi-colon(;). Within each row, elements are separated by # space or the comma(,). Commands and variables used in MATLAB are case-sensitive. That is, lower case letters are distinguished from upper ease letters. The size of the matrix is cheeked with >> size(A) ans=3 3 ‘Transpoxe of a matrix In order to find the transpose of matrix A, we type >> a ‘The result is 120 ans= 3 T 3 629 Column or row components MATLAB provides columnwise or rowwise operation of a matrix. The following expression >> Al3) yields which is the third column of matrix A. In addition, er AL) represents the first row of A as ang=i 30 ‘We can also try >> A(1,:)+.4(3,:) as addition of the first and third rows of A with the result ane=1 6 15 Now let us introduce another matrix B as >> B= [3,4,5:6,7,2:8,1,01; ‘Then there seems to be no output on the screen. MATLAB does not prompt output on the sereen wlien an operation ends with the semi-colon(;) at the end. Tf we want by check the Boaalsin again, we simply type >> B ‘The screen output will be 4 Introduetion to MATLAB Chapter £ & " mae nae Matrix addition Adding two matrices is straightforward Uke >> C=A4B 47 c=8 14 10 e449 ‘Thus we defined a new matrix C' as cum of the previous two matrices Matix subtraction In order to subtract matrix # from matrix A, we tye >> Ca A-B -2 -1 1 406 -8 2 9 Nate that Cis now a new matrix not the summation of A and 4 any more. Matrix multiplication Similarly, atzix multiplication can be done a8 >> Ca Awe 69 31 11 = 2 6 24 90 30 6 1.5 Matrix Functions Manipulation of matrices is a key feature of the MATLAB functions, MATLAB is a useful tool for matrix and vector manipulations. Collections of representative MATLAB matrix functions are listed in Table 1.5.1. Examples an¢ detailed explana- tions are provided for each function below. Matrix inverse The inverse of a matrix is as simple as >> inv(A) 408 1.8571 0.4286 —0.8071 0.8571 6.4288 = 0.1905, 0.287 0.1429 0.0476 In order to verify the answer, we can try >> Asinv(A); Section 1.5 Matrix Functions 5 Table 1.5.1. Basic Matrix Rimesions Symbol. Explanation: inv inverse of a matrix det determinant of a matrix rank rank of a matrix cond condition number of a matrix eye(n) the n by m identity matrix trace summation of diagonal elements of a matrix zeros(nym) the n by m matrix consisting of all zeros which should be a 3 by 3 identity matrix. Determinant of a matrix >> d =det(A) produces the determinant of the matrix A. ‘That is, asm Rank af a matrix The rank of a matriv A, which is the number of independent rows or columns, is obtained from prank); Identity matrix >> eye(3) yidlde Loo ans=0 10 ool eyo(n) produces au identity matrix of size n by m. This command is useful when we Initialize a satrix. Matrix of random numbers A matrix consisting of random numbers can be generated using the following MATLAB function >>rand(3,3) 0.2190 0.6793 0.5194 ans= 0.0470 0.9347 0.8310 0.6789 0.3835 0.0346 6 Introduetion to MATLAB Chapter 1 That is, rand(3,3) produces a 3 by 3 matrix whose elements consist of random nuuthers, The general usage is rand(n, mm). trace Summation of diagonal elements of a matrix can be obtained using the trace operator. For example, >> Call 39, 67% 8 -1 —4 Then, trace(G) produces 6, which is the sum of disgonal elements of C. axe umatrin >> aeros(S, 4) produces a 5 by 4 matrix consisting of all sero elements. In general, zetos(n, m) is used for an n by m zero matrix. condition number The command cond(A) is used to calculate the condision number of a matrix A. ‘The condition umber represents the degree of singularity of a matrix, An identity matrix ha a condition number of unity, and the condition number of a singular matrix is infinity. >>cond(ege(6)) ans = ! An example matrix which is near singular is 14 a= [i 1+ 10] The condition number is >>eond(A) 4000004006 Further matrix functions are presented in Table 1.5.2. They do not inelide all matrix fonctions of the MATLAB, but represent only a part of the whole MATLAB functions. Readers can use the MATLAB Reference’s Guide or help command to cheele when they need more MATLAB functions. Matrix exponential The expma(A) produces the exponential cf a mabrix A. Ia other words, >> A srand(3, 3) 0.2190 0.8793 6.5194 A= 0.0470 0.9347 0.8310 0.6789 0.3835 0.0346 Section 1.5 Matrix Funetions 7 ‘Table 1.5.2 Basic Matrix Functions (Gonnued) Symbol Explanations expm exponential of w matrix —_ eig eigenvalues/eigenvectors of a matrix la LU decomposition of a matrix ovd singular volue decomposition af a matrix QR decomposition of a masrix used Wo solve a set of linear algebraic eq >>expm(A) 1.2448 0.0305 0.6196 ans = 1.0376 L5L16 13380 1.0187 0.1184 2.0652 Bigenvalues The cigeuvalue proviern uf « umria is defined os Aga dd where ) is the eigenvalue of matrix A, and ¢ is the associated sigenvector. vy e selg() gives the eigenvalues of A, and set) produccs V matrix, whose columns are eigenvectors, and the diagenal matrix D whose valuos are eigenvalues of the matrix A. For example, p> Aa[6 3% 146; 07 >> [V,D] seig(A) 04197 a.5999 9.0889 V = 0.5657 —0.7773 —0.6388 0.7217 O.1918 0.7680 >> [KD] 12.5361 0 0 D o (17486 0 4 Q —a.9R47 LU Decomposition ‘The LY decomposition command is used to decompose a mesrix into a combination of upper and lower triangular matrices, respectively. p>Aa[L 35 248 47 3h >> [L,U] =Iul A) 8 Introduction to MATLAB Chapter 1 9.2500 1.0000 0 = 0.6600 6.4000 1.0000 1.0000 0 0 4.0000 7.0000 3.0000 = 0 1.2500 4.2500 a 0 4.8000 In order to check the result, we try >> LeU 136 ans=|2 4 8 473 ‘Phe lower triangular matrix Fie not perfectly triangular, There is another command available >> [FH P| =Int A) 1.6006 0 0 0.2600 1.0000 8 0.5000 9.4000 1.0000 4.9000 7.0000 3.9000 L = 0 12800 4.2500 0 0 4.8000 oon Pol 00 o10 Here, the matrix P is the permutation matrix anch thet ?+A= LeU. Singular value decomposition The evd command is used for singular value decompcsition of a matrix. For a given matrix, A=uEy’ where Dis a diagonal mattix consisting of non-negative values. For example, we define a matrix D like >> Dall 37 29 %& 28 5] ‘The singular value decomposition of the matrix is >> [V, Sigma, V] =evd(D) which results in 0.4295 0.8998 | - 0.0775 U = | 0.6629 0.6495, 0.6133 0.7564 Section 1.6 Matrix Functions 9 1s.6a92 oD 0 Sigma = [ 0 4.1333 0 | 9 0 0.1891 U.7771 -0.5982 -0.1956 0.1905 -0.0725 9.9790 v= 0.5999 0.7980 —0.0576 QR decompouit! A matrix can be olso decompocad inte combination of an orthonormal matrix and an upper triangular matrix. 1 other words, AZ=QE where Q is the matrix with orthonormal columns, and 2 is the upper triangulac matrix, The Q2 algorithm has wide applications im the analysis of matrices and associated linear systems. For example, 0.0470 0.9347 9.8310 0.2190 9.6793 0.5194 A= [soma 0.3835 9.0346 Application of the ar operator follows as >> [@, 4] =arfA) yields 0.3063 -0.4667 0.8297 Q= | -0.0858 -0.8591 0.5076 0.0407 0.9101 0.9394 R= 6 1.0205 —0.9490 0.7149 -0.6338 —0.2456 8 0 —0.0011 Solution of linear equations ‘The solution of a linear system of equations is frequently needed ia the finite element method. The typical form of a linear gystem of algebraic equations is written as Azzy and the solution is obtained by >> ny (cA) or we can use \ sign as >>as AW For example p> Aa=|l3 4 5 7 8 23 ot 10 Introduction to MATLAB Chapter 1 Table 1.0.1 Dasa Analysis Functions Explanations min( max) minimurn(maximurn) of a vertor sum aum of elements of « vector std standard deviation of a data collertion sort sort the claments of vector mean mean value of a vector used for componentwise operation of a vecior and >> y= [10; 9 a]; Let us compare two different approaches. >> [inv(A)ey Aud —4,2500 —4.2500 ans= 1.750C 1.7500 2.2500 2.2500 1.8 Data Analysis Functions Tip to now, wa diseased matrix related functions and operstara of MATLAB, MA'TLAG hse also data analysia functions for a vector or a columa of a matrix. Ia Table 1.6.1, come operators for data manipulation are listed Minimum (maximum) The min (mex) finds a minimum (maximern) valve of a given vector. Hor example, >> vail 28 78 26 49 92 28 23); >>min(u) yields ans = i >>max(v) ans = 99 sum The sum command produces the summation of elements of a vector. For example, Section 1.6 Data Analysis Functions ul Standard deviation The std command calculates the standard deviation of a vector, For example, >> std(l 4 0 -5 6 9 ~20)) ans = 10.4517 Sort a vector The sort command js used to sort a vector in the ascending order. >> sorti[l 4 10 -5 6 9 —20) ans = -0-51469 19 Moai valuc ofa vecton The uteau valvulates Ure sean yelus uf « veciun >> mean([I 410 -5 6 9 —20)) ans = 0.7143 Vector componentwise operation Let us define two vectors >> v= [1,5,6,75u2 = 0,235); Sometimes we want to multiply components of v; with the corresponding components of ug. ‘The operation is D> Ua = Pde ans = om 18 9% In other words, ( ).*{ ) represents the componeatwise multiplication of two vectors Another useful operator ie D> te = te/r with a= 0 04 05 0.7143 Note that the deta analysie tools explained in the above are applicable to matrices too. Pach matrix column is regarded 5 a vector for data analysis. 12 Introduction to MATLAB Chapter 1 Table 4.7.1 Polynomial Functions Explanations converte collection of roots into = polynomial equation finds the roots of a polynorrial equation evaluates a polynomial for a given value multiply two polynomials decompose a polynomial into a dividend and a residual curve Biting of 2 given polyaomial 1.7 Tools for Polynomials Polynomials are frequently used in the analysis of linear systems. MATLAB provide some tools for handliag polynomials. The sumriary of polynomial funetions is provided in Table 1.7.1. Roots of a polynomial equation A polynomial equation is given by 12" fae" +o pant ang =0 The roots of the polynomial equation is solved using roats command roots([a1 az --- an aa4i]} For example, zt 442° —527+62—9 >>roots([} 4 ~—5 6 —9]) yields 5.23564 1.2008 0.0178 1.1963% 0.0178 - 1.19034 Generation of a polynamial equation nsing enats The poly commend takes the roots, and converts them inio a polynomial equation. Por instance, if we know Tris ran ota) in (erie ra) fer} = 2h beget + age pe tena ton then Section 1.7 Tools for Polynomials a >ppoly([ri, %) -°>, tal) provides us the coefficients{ [a1,a2,--+, dn]) of the polynomial equation. Fer exaznple, >ppoly([-1 —24+24¢ —2—248 —547«¢ —5—T+i]) produces ans = i o15 196 498 968 §92 In order to check the result, we use roots command again. >>roots([! 15 146 498 968 592)) ‘The result should be [-1 —24+2*¢ —2~2ei -5+i#i -5-7ed. Polysumial value When we want ty calculate the value uf a polynomial ab a certain point, we can use polyval. >> yspolyval((1 34 -5 19) ans = 23 which evaluates the polynomial 6? + 367 4 4s -— 5 at Multiplication of two polynomials ‘he conv command is used to muliply two polynomials. For example, a(s)= se? 44s—1, (a) 2s? + 60-7 ‘The multiplication of a(s) and 6(s) follows as >>excomv(l 3-1, -26 -7) 130-27 7 In other words, we cbtain the coefficient vector c of the product of a/s) and 6(s) ion of a polynomial The deconv is used to decampose a polynomial! ae a multiplicend and s residue. Let a{s) = He)m(«) + r(s) That ia, the polynomial a(3} is reprosonted in terms of a nmltiplicand fa} and « residue r(s) via. B(1). The MATLAB command ‘s >> bm,7] =deconv(a,}) where the parameters are ccefficient vectors for given polynomials. An example is given by >» [m,7] =deconv(t -2 6 -7,[1 3-1) m= 14 Introduction to MATLAB Chapter 1 1 6 r= 0 0 22 -12 If we change the order of polynomials, >> [m.r]=deconv({1 3 —1},[1 -2 6 -7) m= Polynomial fit The poly fit command ip to generate » polynomial carve which fits 8 given sel of data, The polynomial is obtained by minimizing the etror between the polynomial and the given data set. The synopsis is p =polyfit(z, y,2) where 2 and y are vectors of the given data cet in (2, y) form, and m is the order of the desired polynomial to fit the data set. The ouiput result is p, the coefficient vecter of ‘the fitting polynomial, An example is provided below, praes[l 2345 6); >>ys[-1 352 -3 1) >> p =polyfit(z,y,1) p= 21714 -1.268T A linear curve fitting is performed for data set (z,x). 1.8 Making Complex Numbers In order to make a complex number 243 ¢ i, we use ep D4 Bel or >> 2+ aed MATLAB tokes 4 and j as a pure complex number. In ctse# or j is defined already, >> i ssqrt(—1) #=0+ 1.0000 Section 1.0 Nonlinear Algebraic Equations 15 ‘Kable 1.9.1 Functions for Nonunear Algeprate Equarions Symbol Explanations fmin finds minimum of » function of one vsrisble frero_| solves anonlinear algebraic equation of one variable abs, angle For a given coraplex number, we use abs and angle commands to find out the magnitude (abs) and phase angle (angle) of the given complex number. For example, if Does lth then >> abs(e} ang = 14142 >> angle(e) ang = 2.3562 Real, imaginary parts of a complex number The real and imag are used to toke the real and imaginary parts of a eomplen aumber, For oxample, W494i >> freak) ,imag(c)] ans =—10 9 ppe= Conjugate The conj command is used to generate a complex conjugate number. For example >> conj(-1+5*#) ans = 1-544 1.9 Nonlinear Algebraic Equations Nonlinear algebraic equations are frequently adopted in many different. areas, The nonlinear equations are different from linear equations, and there is no unique analysis too! to the nonlinear equations. MATLAB is equipped with some functions which can handle nonlinear aquations The list is precented in Tabla 1.01 Minimum of a function The MATLAD command fain minimises 9 funetion by finding out 4 value which minimizes the given function. The synopsis is Hmin(' func’, 22) 18 Introduction lo MATLAB Chapter 1 ‘Table 1.10.1 Numerical Techniques for Ditferential Equations Explanations ede23 | solution using the 2nd/Srd order Runge-Kutta algorithm odet5 solution using the 4th/5th order Runge-Kutta algorithm: where “fune’ is the name of function to be minimised and #,(z2) represents & lower(upper) limit of the interval of the function argument. For example, >pfmin('z + 208(2)', -2,2) produces ana = —0.8603 Solution of a nonlinear algebraic equation When a nonlinear algebraic equation is written as 0 the MATLAB function frero can be used to find solution of the nonlinear algebraic equation. ‘The synopsis is 9434 sin{z) — >> sol =faero(’ function’, 20) where ‘function’ ic a MATLAB function subroutine and #0 is an initial condition veclur of the vatiables. For the given example, we write a function aubroutine fotn.w as fanetion [f] =fetn(2); foad4 2 + cos(z) — 42; Then, ne use fzero command 48 >> sol =frcro(! fetn’,—5) sol = 984 In order to hack the solution >>fotm(—2.1981) ans = 1.9198e-004 The error is due to the numerical dormat error, The number is trunested for screen display purpose, even if it is calculated using dowble precision format inside MATLAB, 1.10 Solving Differential Equations Linear and nonlinear differential equations can be also solved using MATLAB. List of numerical techniques solving differential equations is in ‘lable 1.10.1. Section 1.11 Loop and Logical Statement wv Runge-Kutta second and third order algorithm MATLAB uses the Runge- Kutta algorithm to sclve a differential equation or a set of differential equations. The general synopsis is [é,2] = ode23(' func ,t0, tf, x0) where *fune’ is a function containing the derivative information, 10 (tf) is the initial (final) time, and 20 is an initial condition vector. The outputs are i, which eontaine the returned time points, and x which is the integrated output For oxample, we want. te oolve H+ sin(z) =0 which can be rewritten as fay fq = —sin() where x, = @ and #z =#. The ’fune’ function should be provided as an indpendent function subroutine ax faxc.m in a directory, which MATLAB can locate. Now we execute the odezs command >> [i,2] sode23(' func’, 0, 10, 20); o-{3) is an initial condition and furc.m is provided as Sumctbucs [f] =faue(x); eros(2,1); where Rumge-Kutta Bourth and Pifth arder algorithm There ic snather Runge Katia algorithm ode45 which is more accurate than ode23. [t, 2] = edeas(’ func’, 10, ¢/,20) ‘The came calling synopsis as ode23 can be applicd to make uso of the odedS function. 1.11 Loop and Logical Statement. ‘Phere ove sume logical slatcments available in MATLAB which help us writing combinations of MATLAB commands. Furthermore, loop commands can be used as in other programming languages. In fact, we can duplicate the majority of existing programs using MATLAB commands, which significantly teduces thesive of the source 18 Introduction to MATLAB Chapter L al Statements Table da. Loup aud © Symbol Explanatior for Joop command similar to other languages while used for a Joop combined with conditional statement if produces a conditional statement elsoif, clea used in conjunction with if command break breaks a loop when a condition is satisfied codes. A collection of loop and logical statements in MATLAB is presented in Table LIL, for loop The for is a loop command which eads with end command, In the above example, iis a loop index which starts from 1 and ends at 100. There may be oloo multiple Ioopa. >> for i 100 for j=1:50 for k= 1:60 ) = AGA) weld) ta end while The while command is useful for an infinite loop in conjunction with a conditional statement. The general synopsis for while command is a8 follows while condition statements end For example, 1 while (5 < 100) gait; end Another example of the while command is = 1000; var =]; Section 1.11 Loop and Logical Statement 19 while (n > 0) n=nft—1; var = (ear, es end ‘The result ic vat = Cohumns 1 throngh 6 4,9900e+002 2.4850c+002 1.2325e4002 §.0625e+4001 2.9313e4001 1.3856e+001 Columns 7 through 9 5.8281e+000 1.914Je+000 -4.2969e-002 where we used [ ] iu order vo dedare au exupty matrix, if, elseif, else The if, elseif, and else commands are conditional statemenis which are used in combination. if condition #1 staternent #1 elseif condition #2 stuteruent #2 else atoternent #3 end For example, n= 10; if (rem(n,3) == 0) 2=0; elseif (rem(n,3) == 1) eal where rem(x,y) is used to calculate the temainder of z diviced by y. break The break command is used to exit from a loop such as if and while, For cxample, if(¢== 10) break; end end 20 Introduction to MATLAB Chapter 1 Table 1.11.2 Loop oud Logical Statearenes Symbol Explanations twa conditions are equal = two conditions are not equal <=( >=) | oneis less (greater) than or equal to the other fone ia Teas (greater) than the other & and operator - two conditions are met not operalor I or operaice - either one condition is met Logical and relational operators The logical and relational operators of MATLAB are as listed in ‘Table 1.11.2. The above command sets are used in combination, 1.12 Writing Function Subroutines MATLAB provides a convenient tool, by which we can write a pregram using collections of MATLAB commands, ‘This approach is similar to other common programming languages. It is quite useful especially when we write a series of MATLAB commande in a text file. Thio text file ic edited and omved for lator noc ‘The text file should have fileneme.m format normally called m-jile. That is, all MATLAB subroutines should end with .m extension, so thai MATLAB recognizes them as MATLAB compatible files, The general procedure is to make a text Mle using any text editor. If we generate a file called func.m, then the file funed.ma should start with the following file header fanetion[ou ,ovg,...] = func (ins,ivp, where iu,,it,... ate input variables while ovy,oo2,... are output variables. The input variables are specific variables and the output variables are dummy variables, for which we can use any varinbles. For example, let us solve a second order algebraic equation. az? +br+e=0 ‘The sulution is given in analytical form as abt VPN Teaee Qe Section 1.12 Writing Function Subroutines a We want to write an m-file with the name secrvot.m, which produces the analytical solution. fimetion [r1,r2]=secroot(a,t,¢); % % Pind Determinant —— Any command in MATLAB which starts with % % sign is a comment statement Det = 02 —4waxc; if (Det <0), baja agrt(—Det\/Ifa b= jx egrt(—Det})/2/a; disp('The two roots are complex conjugates’); disp('There are two repeated roots‘); dlse(Det > 0) Bt agré(Det))/2/a; —b— sqrélDet))/2/a; disp(‘The two roots are real’); end Some commands appearing in the above example will be discussed later. Once the secroot.m is created, we call that function as >> [Pl r2]=seeroot(3, 4,5) or >> Ppl. p¥] Ssecroot(3, 4,5) One thing important about the function command is to set up the mefle pathname. The mafile should he in th ditectory which is set up by MATLAB configuration set up slage. In the recent version of MATLAB, the set up procedure is relatively cacy by aimply adding a directory which wo want to accoea in a MATLAB configuration file. Another function subroutine fct.m is provided belov. function [f] =fet(x) fa 272) ‘The above function represents f(z) = (1—)®. In the MATLAB command prompt, we call the function as =fct(9); The function subroutine utility of MATLAB allows users to write their own subrou- tines. It provides flexibility of developing programs using MATLAB. >> 22 Introduction to MATLAB Chapter 1 ‘Tablo 1.19.1 File Manipolation Commands. Symbol Explanations save gave current variables in a file load Joad a saved file into MATLAB environment diary save screen display output in Lext format 1.13 Pile Manipulation Manipulating files is another attractive feature of MATLAB. We can save MATLAB workspace, that is, all variables used, in a binary file format and/or text file format. The saved file can be also reloaded in case we need it Inter on. The list of fle manipulation commands is presented in Table 1.13.1. sava The eave command is naed to save variahles when we are working in MATLAB. ‘The synopsis is aa follows gave filename wary vers os where jilename is the filename and we want to save the variables, var, vary, .... The filename generated by save command has extension of -tmai, called a mat-file. If we do not include the variables name, then all current variables are saved automatically. In case we Want to save the variables in a standard text format, we use save filename vary vurg ..fascii/doutte Joad The load command is the counter-part of save. In other words, it reloads Uhe variables in the file which was generated by save command. The synopsis is ax follows load filename var: varz where filename is matyfile saved by save command, Without the variables name specified, all variables are loaded. For example, ppas[i 3 4}; >> b= 3; >>save test >pelear all % clear sll variables >>who ‘% display current variablea being used >>load test >>who ary Using diary comand, we cm capture all MATLAB teats including command. and answer lines which are displayed on the screen. The vexts will be saved in a file, 80 that we can edit the file later. For example, >odiary on Section 1.14 Basic Input/Output Functions 23 Table 1.14.1 Inpul-Outpal. Kunetions Symbol Explanations input save current variables ina file disp load a saved file into MATLAB environment format check the file status in the directory poashbadies pola be] >> daanh presgth >>diary off Now Wwe can use any 1exXt editor to modify ihe #tary Me, ‘The diary command 's useful displaying the past. work procedures. Also, it can be used to save datn in text format, 1.14 Basic Input-Output. Functions Input/output functions in MATLAB provide MATLAB users a friendly pro- gramming environment. Some input/output functions ate listed in Teble 1.14.1. imput The input command is used to receive a user input from the keyboard. Both pumerical and string inputs ars available. For oxample, >> age= imput('Houw Old are you?’) >> name =input('What is your name’, s') ‘The ’s? sign denotes the input type is string. disp ‘The disp command dispiays a string of text or numerical values on the screen. It is useful when we write a function subroutine in a user-friendly manner. For example, pe disp(‘This is a MATLAB tutorial’) >> disp('‘The computed value of ¢ turns owt 10 bc) pre format ‘The format cormand is used to display narsbers in different formats, MATLAB calculates floating numbers in the double precision mode. We do uot want to, in some situations, display the numbers in the double precision format on the sereen, For a display purpose, MATLAB provides following different forrnats ppr=l/o 24 Introduction to MATLAB Chapter 1 Table 125-1 Mowing Commands Symbol Explanations plot basic plot command xlabel{ylabel) attach label to x(y) axis axis meanuelly scale x and y axes tont place s toxt an the spacific pasition of graphic eeroen title place a graphic title on top of the graphic ginput produce a coordinate of a point on the graphie screen gtoxt reteives a text fram mouse input grid add a grid mark to the graphic window pause hold graphic acroen until keyhonrd ia hit subplot breaks a graphic window into multiple windows x= O11 >>format short ¢ z= Lille—001 >>format long w= DPIILHI1LI1LI1 >aformat long ¢ AULLLU11101 Le — 001 pofurmat hex SfbeTe7cPle7le 1.15 Plotting Tools MATLAB supports some plotting tools, by which we cen display the data in a desired format. The plotting in MATLAB is relatively cnay with various options available. The collection of plotting commands is listed in Table 1.15.1 A sample plotting command is shown below. 0.4: 105 y= sin(t); >> plot(y) >> title plotty)) Section 1.16 Plotting Tools 25 ‘The resultant plot is presented at the top of Fig. 1.16.1. >> b= 0:01:10; >> y= sin(t); >> plot, y) >> title('plat(y)’) The resultant plot is presented at the bottom of Fig. 1.15.1. In the above example, += 0: OL : 10 represents a vector ¢ which starts from 0 and ends at 10 with an interval of 0.1. We can use just y or both y and ¢ together. In the tirst case, the horizontal axis represents number of data, from 0 to 103. In the second case, the horizontal axis is the actual time scale ¢ in the plot(t,y) command. Plotting inultiple data We plot multiple data sets as shown below. 0:4: 100; sin(t). #4 ros(t) ets >> plot(tiyd, 4492," ) where ‘-’ and "—’ represent line styles. The line styles, line marks, and colors are listed in Table 1.15.2. For example, if we want to plot a data in a dashed blue line, the command becomes >> plot(y,’4 xdabel, ylabel The xlabel('text’) end ylabel(‘text’) are used to label the and y axia The axis command sets up the limits of axes. ‘The eynopsis is aaxishitmins Zmae: Ymins trae) text The text command is used to write a text on the graphic window at a designated point. The synopsis is text(s,y,{text contents’) ‘where 2, y locates the 2, ¥ position of the ‘text conzenzs'. In case we want 1 aormalize the graphic window size fom 0 to 1, we use toxt(2,ytext contents / se’) input This command allows us to pick up any point on a graphic window. The synopsis is (t,9) = ginput 28 Introduction to MATLAB ol as} 04} oat pe potty) oe on} os oa} aa a9} 4, Figure 1.19.1 A Sample Plot Chapter 1 We can pick as many points as we want on the graphic screen, ‘The welor [2,9] then contains all the peints. gtext The gtext command is used to place a text on the graphic window using the mouse input. The synopsis is gtext(‘teat') Section 1.15 Plotting Tools x Table 1.26.2 Line, Mark, aud Golor Styles Style Line marks Color solid point. rel or dashed = *~’ star * aren dotted "2 cirde 0 blue b dackdot 7." plus 4 white _ x-tnark invisible i Once the above command is entered or read in a function subroutine, the cursor on the graphic window is activated waiting for the mouse input, #0 that the “tar? is located at the point selected by the mause. grid ‘The grid cemmand adda grids to the graphir window It is useful shen we want to clarify axis scales. An example plot constructed using some of the commands described above is presented in Fig. 1.15.2. ‘The following commands are used for the plot oxtput. e> #20:0.1:205 >> plottt, san(t)) >> xlabel('Time(see}’)} >> ylabel(’ydata') >> title('This is a plot example’) >> erid >> gtext('sin(:)') >> axds((0 20 - 1.5 1.5) pause This command is useful when we display multiple grapbie windows sequen tially. It allows us to display one at a time with the keyboard interrupt. subplot The subplot is used to put multiple plots on the same MATLAB figure window, The command is >> subplot(pgr) ‘The plot cise is adjusted by a p by g matrix on the whole-sige of the geaphie window. ‘Then the third index r picks one frame out of the p by q plot frames, Av exanple subplot is presented in Fig. 1.18.3 with the following commands entered. pe eS 0: 01 De piyy = sin(e)jx = c0a(s); >> subplot (222) ve plot(s,y) 3> title('x and y?} >> subplot(223) >> plot(z,2) 28 Introduction to MATLAB Chapter 1 ‘Theis a pleteoargla Figure 1.15.2 A Plot Example With Some Commands xewy as| asl x * 7% and os] es| q a oa Figure 1.15.8 A Subplot Example >> title(x and 2’) >> subplot(224) >> plotiz,y/ Section 1.15 Plotting ‘Lools >> tith('x and [y 7} where pi is an internally defined variable equivalent to 7. CHAPTER TWO APPROXIMATION TECHNIQUES 2.1 Methods of Weighted Residual Methods of weighted residual are useful to obtain approximate solutions to « differential governing equation, In order to explain the methods, we consider the —, O

You might also like