aaaa

Attribution Non-Commercial (BY-NC)

8 views

aaaa

Attribution Non-Commercial (BY-NC)

- Representing Rubik's Cube in Apl
- Spatial Econometric With Matlab
- matlab
- AbstractAlgebra_ArtinAlgebra
- Accelerated Math II - Unit I-1
- Wheel-Rail Contact Element
- Matlab Course Training Details
- Syllabus12
- 1 Matlab Introduction
- Revision for Java Programming I Basic
- simulink_4
- Python Tutorial
- Mat Lab Plotting 2
- TalesoftheArabianNights_v1.1
- matlab
- Octave Basics
- Extra Material Matlab
- zdate_fun
- matlab 1
- 9780387981840-c1

You are on page 1of 11

3: Introduction to MATLAB

MATLAB is a sophisticated software package and we are only going to touch upon a few of its capabilities within this book. MATLAB is essentially a powerful programming language; one of the reasons that it is so powerful is that its basic data structure is the array. Therefore, you can solve problems that involve large vectors and matrices intuitively and manipulate the results easily. MATLAB is used in this book almost exclusively for carrying out numerical simulations. All of the examples in this book that use MATLAB were completed using MATLAB Version 7. These examples could be solved with little or no modifications using earlier versions of MATLAB. Additional information concerning MATLAB can be obtained from the distributor. MATLAB 7 The MathWorks, Inc. http://www.mathworks.com/ 1-508-647-7000

When you open MATLAB, you will be in the Command Window or working environment, as shown in Figure A.3-1. This is the set of tools and facilities that you work with as the MATLAB user or programmer. The working environment includes facilities for managing the variables in your workspace and importing and exporting data. There are also tools for developing, managing, debugging, and profiling M-files, which are MATLAB programs or applications. Notice the windows that show the Command History (the list of commands that you executed previously; these can be cut and pasted back into the Command Window to re-execute them) and the window which shows both the files in the current directory (Current Directory tab) and the variables currently in the workspace (Workspace tab). You can change the directory that you are working in from within the Current Directory tab. You can enter variables and manipulate them, call functions, etc. in the working environment. The commands are entered at the command-line prompt (>>). The best way for you to get started with MATLAB is to learn how to enter and manipulate matrices as these are the fundamental data type used by MATLAB. In MATLAB, a matrix is a rectangular array of numbers; special meaning is sometimes attached to 1-by-1 matrices (i.e., scalars) and to matrices with only one row or column (i.e., vectors). The operations in MATLAB are designed to be as natural as possible. Where other programming languages work with numbers one at a time, MATLAB allows you to work with entire matrices quickly and easily. Therefore, it is much easier to work with large sets of data (such as the temperature distribution predicted by a numerical simulation) in MATLAB.

E26-1

You can enter matrices into MATLAB in several different ways, including: o manually as an explicit list of elements, o as data loaded from an external file, o generated using functions built into MATLAB, or o generated with your own functions (i.e., your own M-files). To enter matrices manually, you have only to follow a few basic conventions: o separate the elements of a row with blanks or commas, o use a semicolon (;) to indicate the end of each row, and o surround the entire list of elements with square brackets, [ ]. For example, to enter the 3x3 matrix A , shown below:

2 3 1 A= 1 5 1 7 1 2

(A.3-1)

>> A = [2 3 1; 1 5 1; 7 1 2]

Note that MATLAB will echo the results of carrying out each command as it is entered; in this case, MATLAB will display the A matrix that was created after you press the Enter key.

E26-2

A = 2 1 7 3 5 1 1 1 2

The echo can be turned off by using a semicolon after your command (the opposite of Maple where the semicolon requests an echo). For example, typing:

>> A = [2 3 1; 1 5 1; 7 1 2];

would not be echoed in the working environment. If you ever want to see what the MATLAB variable A is, just type A and press the Enter key:

>> A A = 2 1 7 3 5 1 1 1 2

1 b= 2 5

(A.3-2)

>> b = [1; 2; 5] b = 1 2 5

Working with matrices in MATLAB is extremely natural. For example, the solution to the matrix equation:

2 3 1 x1 1 1 5 1 x = 2 or A X = b 2 7 1 2 x3 5

(A.3-3)

E26-3

>> X=A\b X = 11.0000 6.0000 -39.0000

>> help slash Matrix division. \ Backslash or left division. A\B is the matrix division of A into B, which is roughly the same as INV(A)*B , except it is computed in a different way. If A is an N-by-N matrix and B is a column vector..

MATLAB has an extensive help system that can be accessed either by typing help followed by the function you are interested in or by selecting MATLAB Help from the Help menu. To obtain help relative to the use of the exponential function:

>> help exp EXP Exponential. EXP(X) is the exponential of the elements of X, e to the X. For complex Z=X+i*Y, EXP(Z) = EXP(X)*(COS(Y)+i*SIN(Y)). See also expm1, log, log10, expm, expint. Overloaded functions or methods (ones with the same name in other directories) help sym/exp.m Reference page in Help browser doc exp

The details of the help message may differ depending on what version of MATLAB you are using; however, the specific capabilities of MATLAB that we will be using should be compatible with any version later than 5.0. Note that, unlike EES, variables in MATLAB are case-sensitive. Typically, we will be assigning or addressing the elements in a vector or array using subscripts. The element in row i and column j of matrix A is denoted by A(i,j). For example, A(2,1) is the number in the second row and first column; for matrix A in Eq. (A.3-1), A(2,1) is 1 and A(3,1) is 7. If you want to change the value of A(2,1) from 1 to 8, simply re-assign it:

>> A(2,1)=8; >> A A =

E26-4

2 8 7

3 5 1

1 1 2

It is possible to extract or manipulate entire rows or columns of a matrix. To obtain the 2nd column of A , use the : symbol which indicates all entries; therefore, A(:,2) would indicate all rows and column 2.

>> A(:,2) ans = 3 5 1

The mathematical operators +, -, *, / etc. have their typical meanings when applied to scalar arguments. However, if these (and any) operator is applied to a matrix then the operator will refer to the matrix form of the operation. For example, Ab is the matrix multiplication of the matrix A by the vector b (you may need to review your linear algebra to remember what this means):

>> A*b ans = 13 23 19

The order matters for matrix multiplication; that is b A will not be equal to Ab , in fact, b A is not even possible, as you cannot multiply a 3x1 matrix with a 3x3 matrix:

>> b*A ??? Error using ==> mtimes Inner matrix dimensions must agree.

You may want to avoid carrying out matrix operations and, instead, operate on each element in a matrix individually. This can be accomplished by placing a period (.) in front of the operator. For example, the operation A*A leads to the matrix multiplication of A by itself:

>> A*A ans = 35 63 36 22 50 28 7 15 12

E26-5

E26: Appendix A.3: Introduction to MATLAB whereas the operation A .*A leads to each element in A being squared.

>> A.*A ans = 4 64 49 9 25 1 1 1 4

The results are quite different and most beginners with MATLAB will forget that commands are interpreted according to operations on matrices.

MATLAB is both a programming language and an interactive computational environment. The files that contain code in the MATLAB language are called M-files; the easiest way of developing a numerical solution is as an M-file because it can be saved, manipulated and debugged without having to be re-typed in each time. You create M-files using a text editor and then access them from the working environment as you would any other MATLAB function or command. There are two kinds of M-files: o Scripts, which do not accept input arguments or return output arguments. Scripts operate on data contained in the workspace and are exactly equivalent to typing commands directly into the workspace. o Functions, which can accept input arguments and return output arguments. Functions do not operate on the data in the workspace and can only access variables that are local to the function. The easiest way to create an M-file is to select File>New>M-file; this will open an M-file editor where you can enter the code and save the file for later use. You can save your M-files in any directory that makes sense. However, in order to run the file from the MATLAB environment you need to make sure that the file is located in a directory that is in MATLABs search path. To place a new directory in the search path, type the command pathtool and then click the Add Folder button in the Set Path dialog window that pops up (shown in Figure A.3-2 for MATLAB release 7) and navigate to the directory that you want to add.

E26-6

When you run a script, MATLAB simply executes the commands that are contained in the Mfile. Scripts can operate on existing data in the workspace, or they can create new data on which to operate. Although scripts do not formally return output arguments, any variables that they create remain in the workspace and can therefore be used in subsequent computations. In addition, scripts can produce graphical output using functions like plot. Functions are M-files that can accept input arguments and return output arguments. The name of the M-file and of the function should be the same. Functions operate on variables within their own workspace which is separate from the workspace at the MATLAB command prompt. Both types of M-files will be needed to generate numerical solutions to heat transfer problems. Open a new M-File and save it as practice.m in a directory that is contained in MATLABs search path. Comments can be used to clarify the code contained in M-files. Comments are indicated by the % symbol; anything following the % symbol is not executed. In your practice.m script, specify the radius and calculate the area of a disk:

r=2; %radius of disk A=pi*r^2; %area of disk

Save the file and execute it from the main workspace; nothing appears to happen but if you type r or A then you can see that these variables have been assigned.

>> practice >> A A = 12.5664

E26-7

>> r r = 2

One of the nice things about using MATLAB is that it is easy to debug as you go along; for example, if you were unsure as to the value of r in the script then simply remove the semicolon:

r=2 %radius of disk A=pi*r^2; %area of disk

and MATLAB will echo the value to the workspace as it executes the script.

>> practice r = 2

Scripts can be turned into functions. The header of the function has the format: function[output argument(s)]=function name(input argument(s)) The keyword function tells MATLAB that you are creating a function rather than a script. In MATLAB (unlike EES) more than one output argument can be returned from the function; these go in the square brackets. For example, our script practice.m can be turned into a function that takes r as an input and returns A as an output:

function[A]=practice(r) A=pi*r^2; %area of disk

You can call the function practice from any other function or the main workspace.

>> A=practice(1) A = 3.1416

It is important to understand that functions have their own workspace and only communicate with the calling workspace via the input/output protocol. For example, we could try to re-assign the input argument r within the function:

function[A]=practice(r) A=pi*r^2; r=5; %area of disk %attempt to re-assign r

Executing practice will not affect the value of r in the workspace. E26-8

MATLAB allows the use of programming constructs that should be familiar to anyone who has used a formal programming language like FORTRAN, Basic, etc. However, you may not be familiar with these other languages; this section introduces a few of the most commonly used logic statements. The if/else statements are very common and useful. These logic statements are used to conditionally execute a statement or set of statements based on an expression. For example, we could rewrite the practice.m function so that it returns the area of a disk if r<5 and otherwise it returns the value 999.

function[A]=practice(r) if(r<5) A=pi*r^2; else A=999; end

%area of disk

Note that the statements within the if and else statements are indented; this is good form and makes it very easy to understand the structure of the code. Execute the function practice from the workspace and check if it is working.

>> practice(1) ans = 3.1416 >> practice(6) ans = 999

Notice that the if statement is not followed by then as in most languages. Also, the relational operators are familiar with the exception of equality, which is indicated by = = rather than =; to see the list of relational operators (and other things) type help < in the workspace. Finally, dont forget that all of these programming constructs must be terminated with an end keyword.

E26-9

E26: Appendix A.3: Introduction to MATLAB The for loop is analogous to the DUPLICATE statement in EES; it executes a statement (or several statements) a specific number of times. It will not be possible to carry out numerical solutions to heat transfer problems without using a for loop. The for keyword is followed by an integer variable and a range; e.g., for i=1:10 statement(s) end would execute the statements sandwiched between for and end 10 times; each time the variable i would take on a different value. We can make the function practice return a 10x1 vector in which the first element is the input argument r and each subsequent element is twice the previous one:

function[A]=practice(r) A(1,1)=r; for i=2:10 A(i,1)=A(i-1,1)*2; end

>> practice(r) ans = 1 2 4 8 16 32 64 128 256 512

By nesting for loops you can generate or operate on matrices rather than vectors. Finally, the while statement repeats a set of statement until some break condition is met; often, the while statement is used to terminate an iteration process within a numerical method based on achieving convergence. Here we can rewrite the practice function so that it stops adding values to the vector when they get larger than 4000.

i=1; A(i,1)=r; while(A(i,1)<4000) i=i+1; A(i,1)=A(i-1,1)*2; end

E26-10

There are many other capabilities of MATLAB and we will introduce several additional aspects of the software in the context of various problems; however, this should be sufficient to get you started.

E26-11

- Representing Rubik's Cube in AplUploaded byLuis Felipe
- Spatial Econometric With MatlabUploaded byDaniela Lima
- matlabUploaded byAreef Ahamad Shaik
- AbstractAlgebra_ArtinAlgebraUploaded bySatyavir Yadav
- Accelerated Math II - Unit I-1Uploaded byShuchi Patel
- Wheel-Rail Contact ElementUploaded bycathalbowe
- Matlab Course Training DetailsUploaded bypkumarmys
- Syllabus12Uploaded byVjPratz
- 1 Matlab IntroductionUploaded byazreescribd
- Revision for Java Programming I BasicUploaded byRyan Tang
- simulink_4Uploaded byjoquispe
- Python TutorialUploaded bytomsds5310
- Mat Lab Plotting 2Uploaded bySathish Selvamani
- TalesoftheArabianNights_v1.1Uploaded byalbrackin
- matlabUploaded bySuhail Dar
- Octave BasicsUploaded bySanjayan PradeepKumar
- Extra Material MatlabUploaded byMuchtar Lubis
- zdate_funUploaded bysbaciak
- matlab 1Uploaded byapi-347851515
- 9780387981840-c1Uploaded byXianju Yiang Li
- Display Lines in Boxes in SapscriptUploaded byEmilS
- Matlab_tutorial_rapido.pdfUploaded byAlafael Araújo
- RPT MATH F5 2011Uploaded byaj030608
- My Matlab3Uploaded byLizzy Hsueh
- PLAN-J Mathematics Form5 2012.docUploaded bySuhailah Salip
- HW1_ENED1090_AUTUMN_2014Uploaded byBill Williams
- C++Uploaded byHimanshu Pathak
- Advanced Vision Guided Robotics Steven PrehnUploaded byLeo Ríos
- Q02Uploaded bysaheb_ju
- FunctionsUploaded byHermie Timario

- ACMP 706-210 Ammunition-Series-Fuzes-USA-1969.pdfUploaded bymaru1318
- EDH - Solid Propellants Part 1Uploaded bydrdoak123
- Chapter on Bessel Functions v2Uploaded bydrdoak123
- Section 2.6.3 Gauss SeidelUploaded bysamtt_29
- Appendix a.5 (Economics)Uploaded bydugarias
- Section 8.6.2 Counter-Flow ConfigurationUploaded bydrdoak123
- Section 2.7.1 FEHTUploaded byCarina Oliveira
- Section 3.5.5Uploaded bydrdoak123
- 4-4 Self-Similar Solution - Flat PlateUploaded bydrdoak123
- Section 6.3Uploaded byEdg Miranda
- Section 8.10.5Uploaded bydrdoak123
- Section 1.1.2 Thermal Conductivity of a GasUploaded byGho Vinsen
- Section 3.5.4Uploaded bydrdoak123
- Section 2.3Uploaded bydrdoak123
- Appendix a.2 (Maple)Uploaded bydrdoak123
- Section 5.4.2 Fully Developed Flow in a Circular TubeUploaded bydrdoak123
- Section 8.6.4 Solution With Axial ConductionUploaded bydrdoak123
- The Reynolds EquationUploaded byr27kumar
- Section 3.7Uploaded bydrdoak123
- Section 3.9Uploaded bydrdoak123
- Section 6.4Uploaded bydrdoak123

- Runlenght Compression Techniques for Fpga ReconfigurationUploaded bySameer Nandagave
- Band Pass Filter Design Part 2. Band Pass Filters From First Principles Richard Harris G3OTKUploaded byopacheco
- F6 Maths 2012 1stExam Paper1answerUploaded byUniversityJC
- BrochureUploaded byErldc Control Room POSOCO
- E301Uploaded byKayla Dollente
- Add Math Spm - EnglishUploaded byDin Ika
- The Atlantic Monthly, Volume 05, No. 30, April, 1860 by VariousUploaded byGutenberg.org
- Full Length Practice Test - 08Uploaded byAbhishek Arora
- Don't Gamble With Physical Properties for SimulationsUploaded bylaiping_lum
- An Implementation of Maximum Power Point Tracking Algorithms for Photovoltaic Systems using Matlab and Arduino based RTOS systemUploaded byIJSTE
- Unit 4 SamplingUploaded bySachin Raikar
- Hyperthermia Nature 2011Uploaded byonynho
- C. D. C. Reeve - Substantial Knowledge~ Aristotle's Metaphysics - Hackett Publishing CompanyUploaded byAnonymous 71rWKDJ
- Fluids Lab ReportUploaded byWillybumbum12
- tnl 322 thematic unit pdfUploaded byapi-434244028
- DcomUploaded bydearmohseen
- Cape Open ComsolUploaded byLuis Alberto Guzmán
- Ohm's Law and Its VerificationUploaded byVicky Singh
- mwmanualUploaded bya.huspur
- QUESTION 1Uploaded bydylahmad
- Archimedes MbUploaded byAndre Oliveira
- Physics Prob Set AnswersUploaded byLouie Alvarez
- AB Basic PLC ProgarmmingUploaded byTetsusaiga
- Resources for Geometry a - Congruent TrianglesUploaded byTSPAN
- Sms CgwaveUploaded byjanu
- MUTUAL INDUCTANCE OF ANY TWO CIRCLES By Chester SnowUploaded bymarkrichardmurad
- MetricsUploaded byVinesh
- ss qbUploaded byTapan Kumar Pradhan
- ANU MATH2405 Notes - 1Uploaded byJames King
- Testing 20Uploaded bymukymba