1. Trang chủ
  2. » Kỹ Thuật - Công Nghệ

engineering and scientific computations using matlab - sergey e. lyshevski

240 609 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 240
Dung lượng 18,03 MB

Nội dung

Engineering and Scientific Computations Using MATLAB@ Sergey E Lyshevski Rochester Institute of Technology @KE:icIENCE A JOHN WILEY & SONS, INC., PUBLICATION This Page Intentionally Left Blank Engineering and Scientific Computations Using MATLAB@ This Page Intentionally Left Blank Engineering and Scientific Computations Using MATLAB@ Sergey E Lyshevski Rochester Institute of Technology @KE:icIENCE A JOHN WILEY & SONS, INC., PUBLICATION Copyright 2003 by John Wiley & Sons, Inc All rights reserved Published by John Wiley & Sons, Inc., Hoboken, New Jersey Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4470, or on the web at www.copyright.com Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 11 River Street, Hoboken, NJ 07030, (201) 748-601 I , fax (201) 7486008, e-mail: permreq@wiley.com Limit ofLiability/Disclaimer of Warranty: While the publisher and author have used their best efforts in preparing this book, they make no representation or warranties with respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose No warranty may be created or extended by sales representatives or written sales materials The advice and strategies contained herein may not be suitable foi-your situation You should consult with a professional where appropriate Neither the publisher nor author shall be liable for any loss ofprofit or any other commercial damages, including but not limited to special, incidental, consequential, or other damages For general information on our other products and services please contact our Customer Care Department within the U.S at 877-762-2974, outside the U.S at 17-572-3993 or fax 17-572-4002 Wiley also publishes its hooks in a variety of electronic formats Some content that appears in print, however, may not be available in electronic format Library of Congress Cataloging-in-Publication Data is availablr lSBN 0-47 1-46200-4 Printed in the United States of America 10 CONTENTS Preface vii About the Author X MATLAB Basics 1.1 Introduction 1.2 MATLAB Start 1.3 MATLAB and Demo Help References 1 MATLAB Functions, Operators, and Commands 2.1 Mathematical Functions 2.2 MATLAB Characters and Operators Commands 2.3 MATLAB References MATLAB Problem Solving and 3.1 Starting MATLAB 3.2 3.3 Basic Arithmetic Features How to Use Some Basic MATLAB Scalars and Basic Operations with Scalars 3.3.1 3.3.2 Arrays, Vectors, and Basic Operations Matrices and Basic Operations with Matrices 3.4 3.5 Conditions and Loops 3.6 Illustrative Examples References MATLAB Graphics 4.1 Plotting 4.2 Two- and Three-Dimensional Graphics 4.3 Illustrative Examples References MATLAB Applications: Numerical Simulations of Differential Equations and Introduction to Dynamic Systems 5.1 Solution of Differential Equations and Dynamic 5.2 Systems Fundamentals Mathematical Model Developments and MATLAB Amlications 26 27 27 31 32 41 42 42 42 49 50 51 53 13 80 98 99 99 113 125 132 133 133 141 V Contents vi 5.3 Modeling and Computing Using MATLAB References 152 171 SIMULINK 6.1 Introduction to SIMULINK 6.2 Engineering and Scientific Computations Using SIMULINK with Examples References 172 172 185 206 APPENDIX MATLAB Functions, Operators, Characters, Commands, and Solvers References 207 225 Index 226 PREFACE I would like to welcome the reader to this MATLAB@ book, which is the companion to the environment and outstanding Mathworks users manuals I sincerely feel high-performance MATLAB that I have written a very practical problem-solving type of book that provides a synergetic, informative, and entertaining learning experience Having used MATLAB almost 20 years, I have been for challenged to write a coherent book that assist readers in discovering MATLAB its power and effrom ficiency to its advantages and superiority Many books and outstanding MATLAB reference manuals are available The Mathworks user manuals provide an excellent collection of the MATLAB features environfor professional users [ 11, while textbooks [2 - 91 have been used to introduce the MATLAB ment for students Having used the referenced manuals and books with different levels of user and student satisfaction, accomplishment, and success, the critical need to write a focused (companion) book became evident This is the reason that have embarked upon project This book, in addition to being an excellent companion and self-study textbook, can be used in science and engineering courses in MATLAB well as a complementary book In addition to covas ering MATLAB, author has strived to build and develop engineering and scientific competence, the presenting the material visually, numerically, and analytically.Visualization, numerical and analytical delivery features, fully supported by the MATLAB environment, are documented and emphasized in this book Real-world examples and problems introduce, motivate, and illustrate the application of MATLAB MATLAB books and user manuals have been written, published, and distributed Unfortunately, the MATLAB environment is usually introduced in the introductory freshman (or sophomore) course with very limited time allocated to cover MATLAB during the allocated modules This does not allow the instructors to comprehensively cover MATLAB, inclusive books which cover the materiand al in details and depth cannot be effectively used Furthermore, there are many engineers and scienat tists who did not have the chance to study MATLAB colleges, but would like to master it in the every-day practice MATLAB environment Therefore, this book covers introductory example-oriented problems This book is written with the ultimate goal of offering a far-reaching, high-quality, standalone and companion-type user-friendly educational textbook which can be efficiently used in introcourses in undergraduate/graduatecourses or course modules, and as a self-study or ductory MATLAB supplementary book There are increasing demands for further development in high-performance computing environments, and hundreds of high-level languages exist including C, FORTRAN, PASCAL, etc This environment, which is uniquely suited to perform heterogeneous simulabook covers the MATLAB tions, data-intensive analysis, optimization, modeling, code generation, visualization, etc These features are extremely important in engineering, science, and technology To avoid possible obstacles, the material is presented in sufficient detail MATLAB basics are covered to help the reader to fully unenvironderstand, appreciate, apply, and develop the skills and confidence to work in the MATLAB ment A wide range of worked-out examples and qualitative illustrations, which are treated in depth, bridge the gap between theoretical knowledge and practice Step-by-step, Engineering and Scientijk Computations Using MATLAB guides the reader through the most important aspects and basics in vii Appendix: MA TLAB Functions, Operators, Characters, Commands, and solvers ylabel zlabel Y-axis labels for 2D and 3D plots Z-axis labels for 3D plots Table A 10.2.4 Surface, Mesh, and Contour Plots Table A.10.3 Volume Visualization I Plot velocitv vectors as cones in 3D vector field contourslice I Draw contours in volume slice plane curl I Compute the curl and angular velocity of a vector field divergence Compute the divergence of a vector field flow Generate scalar volume data interpst reamspeed Intemolate streamline vertices from vector-field magnitudes I coneplot subvolume volumebounds I Extract subset of volume data set I Return coordinate and color limits for volume (scalar and vector) Table A 10.4 Domain Generation gr iddata Data gridding and surface fitting me s h g rid Generation of X and Y arrays for 3D plots 213 Appendix: MATLAB Functions, Operators, Characters, Commands, and Solvers 14 Table A 10.5 SDecialized Plotting area I Area plot box I Axis box for 2D and 3D dots comet Comet plot compass Compass plot errorbar Plot graph with error bars ezcontour Easy-to-use contour plotter ezcontourf Easy-to-use filled contour plotter ezmesh Easy-to-use 3D mesh plotter e zmeshc Easv-to-use combination meshkontour dotter rose quiver ribbon stairs Plot rose or angle histogram Quiver (or velocity) plot Ribbon plot StairsteD maoh camdolly camlookat camorbit campan campos camproj camroll camta rget camup camva camzoom Move camera position and target View specific objects Orbit about camera target Rotate camera target about camera position Set or get camera position Set or get projection type Rotate camera about viewing axis Set or get camera target Set or get camera up-vector Set or get camera view angle Zoom camera in or out Appendix: MATLAB Functions, Operators, Characters, Commands, and Solvers I daspect pbaspect view viewmtx xlim ylim zlim Set or get data aspect ratio Set or get plot box aspect ratio 3-D graph viewpoint specification Generate view transformation matrices Set or get the current x-axis limits Set or get the current y-axis limits Set or get the current z-axis limits camlight light lighting lightangle mat eria1 Cerate or position Light Light object creation function Lighting mode Position light in spherical coordinates Material reflectance mode Alpha Alphamap A1 im Set or query transparency properties for objects in current axes Specify the figure alphamap Set or query the axes alpha limits Table A 10.9 Color Operations Brighten or darken colormap Caxis Pseudocolor axis scaling Co1orbar Display color bar (color scale) Colordef Set up color defaults Co 1ormap Set the color look-up table (list of colormaps) Graymon Graphics figure defaults set for grayscale monitor hsv2rgb Hue-saturation-valueto red-green-blue conversion rqb2hsv RGB to HSV conversion Rgbplot Plot colormap Shading Color shading mode Spinmap Spin the colormap Surfnorm 3D surface normals Whitebg Change axes background color for plots I Brighten I Table A 10.10 Colormaps Autumn I Shades of red and yellow colormap bone Gray-scale with a tinge of blue colormap contrast Gray colormap to enhance image contrast cool Shades of cyan and magenta colormap copper Linear copper-tone colormap flag Alternating red, white, blue, and black colormap Linear gray-scale colormap gray hot Black-red-vellow-whitecolormap Hue-saturation-value(HSV) colormap hsv iet I Variant of HSV lines Line color colormap prism Colormap of prism colors spring Shades of magenta and yellow colormap 215 Appendix: MATLAB Functions, Operators, Characters, Commands, and Solvers 16 summer winter getappdata isappda ta rmappda ta setappdata I Shades of green and yellow colormap I Shades of blue and green colonnaD Get value of application data True if application data exists Remove application data Specify application data 21 Appendix: MA TLAB Functions, Operutors, Churucters, Commands, and Solvers I refresh saveas axis cla gca I Refresh figure I Save figure or model to desired output format Plot axis scaling and appearance Clear Axes Get current Axes handle Table A 10.17 Obiect Maninulation Reset I Reset axis or figure rotate3d I Interactively rotate the view of a 3D plot I Selectmoveresize I Interactively select, move, or resize objects ginput zoom Graphical input from a mouse or cursor Zoom in and out on a 2D plot Table A 10.19 Region of Interest Dragrect I Drag XOR rectangles with mouse Drawnow I Complete any pending drawing Rbbox I Rubberband box Table A l l Polynomial and Interpolation Functions Table A 1.2 Data Internolation convhull I Convex hull convhu1In I Multidimensional convex hull I Appendix: MATLAB Functions, Operators, Characters, Commands, and Solvers 18 Table A 12 F nctions: Nonlinear Numerical Methods Solve two-point boundry value problems (BVPs) for ordinary differential equations (ODES) &Duet Extract parameters from BVP options structure Bvpinit Form the initial guess for the bvp4c solver bvDset Create/alter BVP options structure bvpval Evaluate the solution computed by the bvp4c solver db1auad Numerical evaluation of double integrals fminbnd Minimize a function of one variable fminsearch Minimize a function of several variables fzero Find zero of a function of one variable ode45, ode23, Solution of ordinary linear and nonlinear differential equations odell3, odel5s, ode23s, ode23t , ode23tb odecret Extract parameters from ODE options structure odeset Create/alter ODE options structure optimget Get optimization options structure parameter values optimset Create or edit optimization options parameter structure Solve initial-boundary value problems for parabolic-elliptic partial PdePe differential equations Ddeval Evaluate the solution computed by the pdepe solver uuad Numerical evaluation of integrals, adaptive Simpson quadrature quadl Numerical evaluation of integrals, adaptive Lobatto quadrature vec torize Vectorize expression bvp 4c blkdiag eye linspace logspace nume1 ones Construct a block diagonal matrix from input arguments Create an identity matrix Generate linearly spaced vectors Generate logarithmically spaced vectors Number of elements in a matrix or cell array Create an array of all ones Appendix: MATLAB Functions, Operators, Characters, Commands, and Solvers rand randn zeros : (colon) Uniformly distributed random numbers and arrays Normally distributed random numbers and arrays Create an array of all zeros Regularly spaced vector ans computer ePs i Recent answer Identify the computer on which MATLAB running is Floating-point relative accuracy j 219 Imaginary number Not-a-Number Number of function arguments inf inputname NaN nargin, nargout na rgoutchk Pi realmax realmin vararg in, vararaout calendar clock cputime date datenum date str datevec eomday etime now tic,toc weekday I cat Imaginary number f Infinitv Input argument name i J-1 Validate number of output arguments Ratio of a circle's circumference to its diameter (x constant) Largest positive floating-point number Smallest positive floating-point number Pass or return variable numbers of arguments Calendar Current time as a date vector Elapsed CPU time Current date string Serial date number Date string format Date components End of month Elapsed time Current date and time Stouwatch timer I Day of the week Table A 13.4 Matrix Manipulation I Concatenate arravs I Appendix: MATLAB Functions, Operators, Characters, Cornman&, and Solvers 220 cross dot intersect ismember setdiff setxor union unique Vector cross product Vector dot product Set intersection of two vectors Detect members of a set Return the set difference of two vectors Set exclusive or of two vectors Set union of two vectors Unique elements of a vector company gallery hadamard hankel hilb invhi1b magic pascal toeplit z wi 1kinson Companion matrix Test matrices Hadamard matrix Hankel matrix Hilbert matrix Inverse of the Hilbert matrix Magic square Pascal matrix Toeplitz matrix Wilkinson's eigenvalue test matrix Table A 14 Matrix Functions and Linear Algebra Table A 14.1 Matrix Analvsis cond Condition number with respect to inversion condeig Condition number with respect to eigenvalues det Matrix determinant norm Vector and matrix norms nu1 Null space of a matrix orth Range space of a matrix rank Rank of a matrix rcond Matrix reciprocal condition number estimate rref, Reduced row echelon form rrefmovie subspace I Angle between two subspaces trace Sum of diagonal elements I ~ , Table A 14.2 Linear Eauations chol Cholesky factorization inv Matrix inverse lscov Least squares solution in the presence of known covariance lu LU matrix factorization lsqnonneg Nonnegative least squares minres Minimum residual method pinv Moore-Penrose pseudoinverse of a matrix qr Orthogonal-triangular decomposition SYmmlq Symmetric LQ method Appendix: MATLAB Functions, Operators, Characters, Commands, and Solvers expm funm logm sqrtm Matrix exponential Evaluate general matrix function Matrix logarithm Matrix square root qrdelete qrinsert Delete column from QR factorization Insert column in QR factorization spdiags sPeYe sprand sprandn sp rand sym Extract and create sparse band and diagonal matrices Sparse identity matrix Sparse uniformly distributed random matrix Sparse normally distributed random matrix Sparse symmetric random matrix Table A 14.7 Full-to-Sparse Conversion find I Find indices and values of nonzero elements full Convert sparse matrix to full matrix sparse Create sparse matrix spconvert Import matrix from sparse matrix external format nn z nonzeros nzmax spalloc spfun spones I SPY Number of nonzero matrix elements Nonzero matrix elements Amount of storage allocated for nonzero matrix elements Allocate space for sparse matrix Apply function to nonzero sparse matrix elements Replace nonzero sparse matrix elements with ones Table A 14.9 Visualizing Sparse Matrices I Visualize sparsity pattern colamd colmmd Column approximate minimum degree permutation Sparse column minimum degree permutation 22 I Appendix: MATLAB Functions, Operators, Characters, Commands, and Solvers 222 colperm dmperm randperm symamd sy m d symrcm Sparse column permutation based on nonzero count Dulmage-Mendelsohn decomposition Random permutation Symmetric approximate minimum degree permutation Sparse symmetric minimum degree ordering Sparse reverse Cuthill-McKee ordering Table A 14.1 I Norm, Condition Number, and Rank condest Estimate the matrix first-norm normest I Estimates the matrix second-norm I Table A 14.13 Sparse Eigenvalues and Singular Values eigs Find eigenvalues and eigenvectors I svds I Find singular values I Table A 14.14 Miscellaneous spparms Set parameters for sparse matrix routines cart2pol cart2sph pol2cart sph2cart Transform Cartesian coordinates to polar or cylindrical Transform Cartesian coordinates to spherical Transform polar or cylindrical coordinates to Cartesian Transform spherical coordinates to Cartesian cumprod cumsum cumtrapz factor inpol ygon ma x mean Cumulative product Cumulative sum Cumulative trapezoidal numerical integration Prime factors Detect points inside a polygonal region Maximum elements of an arrav Average or mean value of arrays I Appendix: M TLAB Functions, Operators, Characters, Commands, and Solvers A median m in perms po a r e a y primes prod rectint sort sortrows std su m trapz va r Median value of arrays Minimum elements of an array All possible permutations Area of polygon Generate list of prime numbers Product of arrav elements Rectangle intersection area Sort elements in ascending order Sort rows in ascending order Standard deviation Sum of array elements Trapezoidal numerical integration Variance de12 diff gradient Discrete Laplacian Differences and approximate derivatives Numerical gradient corrcoef cov Correlation coefficients Covariance matrix conv conv2 deconv filter filter2 Convolution and polynomial multiplication Two-dimensional convolution Deconvolution and polynomial division Filter data with an infinite impulse response or finite impulse response filter Two-dimensional digital filtering Table A 16.5 Fourier Transforms abs ] Absolute value and complex magnitude ancrle I Phaseangle cplxpair Sort complex numbers into complex conjugate pairs fft One-dimensional fast Fourier transform fft2 Two-dimensional fast Fourier transform fftshift Shift dc component of fast Fourier transform to center of spectrum ifft Inverse one-dimensional fast Fourier transform ifft2 Inverse two-dimensional fast Fourier transform ifftn Inverse multidimensional fast Fourier transform i f ftshift Inverse fast Fourier transform shift nextpow2 Next Dower of two unwrap I Correct phase angles dialog errordlg helpdlg Create a dialog box Create error dialog box Display help dialog box 223 Appendix: MATLAB Functions, Operators, Characters, Commands, and Solvers 224 guida ta guihandles movegui openfig Store or retrieve application data Create a structure of handles Move GUI figure onscreen Open or raise GUI figure Table A 17.3 User Interface Development guide I Open the GUI Layout Editor inspect I Disdav ProDertv InsDector class import isa isjava javaArray javaMethod javaobject methods methodsview I Create object or return class of object Add a package or class to the current Java import list Detect an object of a given class Test whether an object is a Java object Constructs a Java array Invokes a Java method Constructs a Java object Display method names Displays information on all methods implemented by a class Table A 19 Serial Port Input-Output Table A 19.1 Creating a Serial Port Object serial Create a serial port object I fgetl fgets fprintf fread fscanf fwrite readasync stopasync Read one line of text from the device and discard the terminator Read one line of text from the device and include the terminator Write formatted data to file Read binary data from file Read data from file and format as text (read formatted data from file) Write binary data to file Read data asynchronously fiom file Stop asynchronous read and write operations Appendix: MA TLAB Functions, Operators, Characters, Commands, and Solvers get set Return serial port object properties Configure or display serial port object properties Table A 19.4 State Change €close I Disconnect a serial port object from the device (close file) iopen Connect a serial port object to the device (open file) record Record data and event information to a file REFERENCES 225 MTUB Release 13, CD-ROM, Mathworks, Inc., 2002 6.5 Index 226 Index Aircraft, 139-141, 162-167 Algebraic equation, 95-97 Arithmetic, 42-48 Arithmetic operators, 65 Array, 51,52,211,218,218 Basic arithmetic, 42 Block diagram, 170, 179-189, 194, 197,20 Buttons, 23 Characters, Circuit, 144, 145, 154-157, 159-161, 167-165 Clear, 24 Color operation, 103,215 Command window, 5,8,43-46 Commands, 32-4 I Conditions, 73-79 Control flow, 208 Converter, 45- 151 Debugging, 209 Demo, 9,16 Demo window, 17-20,39 Differential equations, 133-139, 146-170,218 Dynamic system, 133-151, 163, 190-193 Eigenvalue, 1,62,22 1, 222 Exit, 22 Figure window, 8,9 File window, , Flight servo, 141 Format, 68 Fourier transform, 222,223 Functions, 27-30 Image, 25,26 Induction motor, 195-199 Interactive input, 208 Interpolation, 72,73,2 17 Kirchhoff law, 145 Linear equation, 220 Logic, 66 Logic functions, 207 Loops, 73-79 Mathematical function, 29, 30,47,48,2 1-212 Mathematical model, 141- 15 MATLAB General, 13 MATLAB Icon, Matrix, 8,43, 53-64, 67, 83-89,218-221 Menu bar, 22,23 Missile, 20 Modeling, 141, I52 Movie, 121- 124 Newton law, 141-144 Norm, 67 Object-oriented programming, 208 Ones, Operators, I, 65-67,207 Pendulum, 143, 179-181 Permanent-magnet DC motor, 169-17 1, 187-190,203-205 Pennanent-magnet synchronous motor, 200-202 Plot, 27,45,46,60, 99- 120, 125-132,2 12-2 14 Polynomial, 69-73, 89,90, 217 Print, 216 General purpose commands, 14, 15,37,38 Graphics, 99- I20,2 16 , 17 Quit, 22 Help, 9, 10,33-36,39 Helpdesk, 9, 15 Helpwin, 9, 10,33 Help system, 23,24 Help topics, IO- 13 Help window, 13,36,43 Helpdesk window, 16 Helpwin window, 33 Save, 24 Saving, 24 Scalar, 50-5 SIMULINK, 172-206 1,2, SIMULINK demo window, 174,175, 185 SIMULINK libraries, 182 SIMULINK librarary browser, 183-185 SIMULINK window, 173 227 Index Single-phase reluctance motor, 193, 194 Special characters, 207 Start, String, 25,42,68,209, 210 Symbolic Math Toolbox, 157-161 Symbols, 1,65 Three-dimensional graphics, 13-120, 124, 125 Trigonometric functions, 28 Toolboxes, 7, 18,20-22 Tool bar, 22,23 Workspace window, 5,8,25,43-46 Variable, 49 Vector, 1, 52 Van der Pol equation, 134-137, 176-179 ... Intentionally Left Blank Engineering and Scientific Computations Using MATLAB@ This Page Intentionally Left Blank Engineering and Scientific Computations Using MATLAB@ Sergey E Lyshevski Rochester... Close MATLABusing the Exit MATLAB (Ctrl+Q) command in the MATLABCommand Window (File menu) MATLAB Menu Bar and Toolbar Figure 1.19 illustrates the MATLABmenu bar and toolbar in the Command and. .. operators and characters are reported in Table 2.3 Table 2.3 Scalar and Array Arithmetic with Operators and Characters Symbol + - * and * / and / \ and. \ and A A MATLABStatement atbtc a-b-c a *

Ngày đăng: 08/04/2014, 10:09

TỪ KHÓA LIÊN QUAN