Download essential matlab pdf






















This completely revised new edition is based on the latest version of. Previous ed. Oxford: Butterworth-Heinemann, The fundamentals of MATLAB are illustrated throughout with many examples from a wide range of familiar scientific and engineering areas, as well as from everyday life.

In this book you will learn by doing, avoiding technical jargon, which makes the concepts easy to learn. Throughout, the language is kept simple to ensure that readers at all levels can grasp the concepts. Some prior programming experience would be helpful but not required. This book provides a pragmatic, methodical and easy-to-follow presentation of numerical methods and their effective implementation using MATLAB, which is introduced at the outset.

The author introduces techniques for solving equations of a single variable and systems of equations, followed by curve fitting and interpolation of data. The book also provides detailed coverage of numerical differentiation and integration, as well as numerical solutions of initial-value and boundary-value problems.

The author then presents the numerical solution of the matrix eigenvalue problem, which entails approximation of a few or all eigenvalues of a matrix. The last chapter is devoted to numerical solutions of partial differential equations that arise in engineering and science. Each method is accompanied by at least one fully worked-out example showing essential details involved in preliminary hand calculations, as well as computations in MATLAB. The main principle of the book is based on learning by doing and mastering by practicing.

Every chapter ends with relevant drill exercises for self-testing purposes. This text provides an introduction that reveals basic structures and syntax, demonstrates the use of functions and procedures, outlines availability in various platforms, and highlights the most important elements for both programs.

Self-contained, it allows the reader to use the material whenever needed rather than follow a particular order. Compatible with both languages, the book material incorporates commands and structures that allow the reader to gain a greater awareness of MATLAB and Octave, write their own code, and implement their scripts and programs within a variety of applicable fields. Includes brief, simple code that works in both MATLAB and Octave Provides exercise sections at the end of each chapter Introduces framed examples and discussions with a scientific twist Exercises are provided at the end of each chapter Essential MATLAB and Octave offers an introductory course in MATLAB and Octave programming and is an authoritative resource for students in physics, mathematics, statistics, engineering, and any other subjects that require the use of computers to solve numerical problems.

Do you like this book? Please share with your friends, let's read it!! Search Ebook here:. Designed by readallbooks. This comprehensive textbook is ideal for engineers, scientists and those in the financial sector who want to grasp the essence of systems modelling and computation.

Popular Books. Fear No Evil by James Patterson. Mercy by David Baldacci. To activate the Array Editor click on a variable in the Workspace browser or right-click to get the more general context menu. From the context menu you can draw graphs of workspace variables in various ways. For example, the following statements can be saved in myconst.

A matrix is a rect- angular object e. A vector is a special type of matrix, having only one row or one column. Vectors are called lists or arrays in other programming languages. MATLAB handles vectors and matrices in the same way, but since vectors are easier to think about than matrices, we will look at them first.

We will also use the term array generally, with vector and matrix referring to the one-dimensional 1D and two-dimensional 2D array forms. These are all examples of the explicit list method of initializing vectors. Exercises 2. Make sure to leave out the semicolon so that you can see the list. Also, make sure you hit Enter to execute the command. Under the head- ing Size you will see that x is 1 by 5, which means 1 row and 5 columns.

You will also see that the total number of elements is 5. Take the space between the minus sign and 15 to see how the assignment of x changes. An empty array may be used to remove elements from an array see Sec- tion 2. The function logspace can be used to generate logarithmically spaced data. It is a logarithmic equivalent of linspace.

If the last number in this function call is omitted, the num- ber of values of y computed is by default Thus, the logspace function produces a set of points with an interval between them that increases linearly with y. The variable yy was introduced for two reasons. The first was to generate a vector of the same length as dy. The second was to examine the increase in the interval with increase in y that is obtained with the implementation of logspace.

Each has one row and several columns. To generate the column vectors that are often needed in mathematics, you need to transpose such vectors—that is, you need to interchange their rows and columns. Note that x itself remains a row vector. Try the following: 1. This gives you a row vector of seven random num- bers.

Enter r 3. This will display the third element of r. The numeral 3 is the subscript. Enter r This should give you the second, third, and fourth ele- ments. What about r and r [1 7 2 6]? You cre- ate a matrix just as you do a vector, except that a semicolon is used to indicate the end of a row. Generate the table of angles and sines as shown above.

Select all seven rows of numerical output in the Command Window, and copy the selected output to the Editor. You can then edit the output, for example, by inserting text headings above each column this is easier than trying to get headings to line up over the columns with a disp statement.

The edited output can in turn be pasted into a report or printed as is the File menu has a number of printing options. Another way of capturing output is with the diary command. The command diary filename copies everything that subsequently appears in the Command Window to the text file filename. Stop recording the session with diary off Note that diary appends material to an existing file—that is, it adds new infor- mation to the end of it.

It is typically written in what is called pseudo- code—that is, statements in English, mathematics, and MATLAB describing in detail how to solve a problem. A structure plan may be writ- ten at a number of levels, each of increasing complexity, as the logical structure of the program is developed. A first-level structure plan might be a simple statement of the problem: 1. Initialize Fahrenheit temperature 2. Calculate and display Celsius temperature 3. Stop Step 1 is pretty straightforward.

Step 2 needs elaborating, so the second-level plan could be something like this: 1. Initialize Fahrenheit temperature F 2. Display the value of C 4.

Stop There are no hard and fast rules for writing structure plans. The essential point is to cultivate the mental discipline of getting the problem logic clear before attempting to write the program.

The top-down approach of structure plans means that the overall structure of a program is clearly thought out before you have to worry about the details of syntax coding. This reduces the number of errors enormously. The results were found to be correct and hence this simple script is, as such, validated. The essence of any structure plan and, hence, any computer program can be summarized as follows: 1.

Input: Declare and assign input variables. Operations: Solve expressions that use the input variables. Output: Display in graphs or tables the desired results. Air resistance is ignored. We would like to compute the value of s over a period of about The structure plan for this problem is as follows: 1.

This plan may seem trivial and a waste of time to write down. Yet you would be surprised how many beginners, preferring to rush straight to the computer, start with step 2 instead of step 1.

It is well worth developing the mental disci- pline of structure-planning your program first. You can even use cut and paste to plan as follows: 1. Paste a second copy of the plan directly below the first.

Finally, paste all the translated MATLAB statements into the Command Window and run them or you can just click on the green triangle in the toolbar of the Editor to execute your script. If necessary, go back to the Editor to make corrections and repaste the corrected statements to the Command Window or save the program in the Editor as an M-file and execute it.

This is called an array op- eration and is different from squaring the vector itself, which is a matrix operation, as we will see later. You might want to save the program under a helpful name, like throw. This way, the plan reminds you what the program does when you look at it again after some months. After you block selected text, right-click to see the context menu.

To comment the text, scroll down to Comment, point, and click. Expressions are constructed from a variety of things, such as numbers, variables, and operators. First we need to look at numbers. For example, 1. This is also called floating-point notation. The number has two parts: the mantissa, which may have an optional decimal point 1. Mantissa and exponent must be separated by the letter e or E. The mantissa is multiplied by the power of 10 indicated by the exponent.

Note that the following is not scientific notation: 1. On computers using standard floating-point arithmetic, numbers are repre- sented to approximately 16 significant decimal digits. The relative accuracy of numbers is given by the function eps, which is defined as the distance between 1. Enter eps to see its value on your computer. As an exercise, enter the following numbers at the command prompt in scien- tific notation answers follow in parentheses : 1.

More information on data types can be found in the Help index. Precedence Operator 1 Parentheses round brackets 2 Power, left to right 3 Multiplication and division, left to right 4 Addition and subtraction, left to right MATLAB also supports signed and unsigned integer types and single-precision floating-point, by means of functions such as int8, uint8, single, and the like.

However, before mathematical operations can be performed on such types, they must be converted to double precision using the double function. The arithmetic operations on two scalar constants or variables are shown in Ta- ble 2.

Operators operate on operands a and b in the table. Left division seems a little curious: Divide the right operand by the left operand. However, matrix left division has an entirely different meaning, as we will see later. The precedence rules for the operators in Table 2. Note that parentheses have the highest precedence. Note also the difference between parentheses and square brackets.

The former are used to alter the precedence of operators and to denote subscripts, while the latter are used to create vectors. Answers are in parenthe- ses. The value 1 is added to each element of the vector In this context, the addition is called an array operation because it operates on each element of the vector array.

Array operations are discussed below. Operator Description. They are sometimes called array or element-by-element operations because they are per- formed element by element. For example, a. You will have seen that a. Now try [2 3 4]. The ith element of the first vector is raised to the power of the ith element of the second vector.

The period dot is necessary for the array operations of multiplication, division, and exponentiation because these operations are defined differently for matrices; they are then called matrix op- erations see Chapter 6. When array operations are applied to two vectors, both vectors must be the same size!

Array operations also apply between a scalar and a nonscalar. Check this with 3. This property is called scalar expansion. Multiplication and division operations between scalars and nonscalars can be written with or without the period i. Answer: [0 -2 3] 2. Assignment always works in this direction. Note that the object on the left-hand side of the assign- ment must be a variable name.

This is useful for suppressing irritating output of interme- diate results or large matrices. Statements may involve array operations, in which case the variable on the left-hand side may become a vector or a matrix. However, it is help- ful to think of commands as changing the general environment in some way, for example, load, save, and clear. Statements do the sort of thing we usu- ally associate with programming, such as evaluating expressions and carrying out assignments, making decisions if , and repeating for.

Functions return with calculated values or perform some operation on data, such as sin and plot. Let us again consider, as an example, the calculation of compound interest. The following program comp. This process is called formula vectorization. The operation in the statement de- scribed in bullet item 1 is such that every element in the vector B is determined by operating on every element of vector A all at once, by interpreting once a single command line.

See if you can adjust the program comp. Hint: use a vector for n: [1 5 10 15 20]. The numerical answers are in parentheses. The answers are in paren- theses. Can you spot the errors in the following expression?

You need to think through the process care- fully. For example, convert 5 acres to hectares, given that an acre is square yards, a yard is 36 inches, an inch is 2. The best approach is to develop a formula to convert x acres to hectares. You can do this as follows. Convert 75 kilograms to pounds.

Convert 40 psi to kPa. Convert 6. You can also use disp to display a message enclosed in apostrophes called a string. If we want to display a string, we create it; that is, we type a message between apostrophes. Note that the last space before the second apostrophe is part of the string. The command more on enables paging of output. This is very useful when dis- playing large matrices, for example, rand ,7 see help more for details. You can begin your search for infor- mation by clicking the question mark at the top of the desktop to open the help documents.

Then search for fopen, a utility which allows you to open a file. Scroll to the bottom of the page in the help manual on this topic and find the following list of functions: fclose, feof, ferror, fprintf, fread, fscanf, fseek, ftell, fwrite. Search for input in the help manual to learn more about this function that is used in a number of examples in this text.

Of course, the simplest input of data is the assignment of values to variables in a program of commands. However, if the integer is too large, it is displayed in scientific notation with five significant digits— is displayed as 1.

Check this by first entering at the command line and then If the value x is in the range 0. Check this by entering the following numbers at the prompt on separate lines : 0.

You can change from the default with variations on the format command, as follows. If you want values displayed in scientific notation floating-point form whatever their size, enter the command format short e All output from subsequent disp statements will be in scientific notation, with five significant digits, until the next format command is issued. Enter this com- mand and check it with the following values: 0.

If you want more accurate output, you can use format long e. This also gives scientific notation but with 15 significant digits. Use format long to get fixed-point notation with 15 significant digits. Use format bank for financial calculations; you get fixed point with two dec- imal digits for cents.

Suppress irritating line feeds with format compact, which gives a more compact display. Use format hex to get hexadecimal display. Use format rat to display a number as a rational approximation ratio of two integers.

Note that even this is an approximation! In certain appli- cations this is a convenient way of displaying matrices. The command format by itself reverts to the default format.

In this example, the common scale factor is , so the elements displayed must all be multiplied by it to get their proper value—for example, for the second element 1. Taking a factor of out of the third element 1e-4 leaves 1e-7, which is represented by 0.

In this section we look at a new feature: repetition. We will first look at some examples of its use, followed by explanations. For starters, enter the following group of statements on the command line. The disp statement is repeated five times, three times, and not at all. This is an iterative repetitive procedure that refines an initial guess.

Here is the structure plan: 1. Initialize a 2. Most computers and calculators use a similar method internally to compute square roots and other standard mathematical functions. Run the following program to generate a list of n and n! You had better leave out the disp statement! Or you can move it from above the end command to below it. The following example also highlights a problem that sometimes occurs when computing a limit.

The question is this: What is the limit of this sequence as n gets indefinitely large? If we try to compute xn directly, we can get into trouble, because n! Each time through the loop it will contain the next element of the vector j :k or j :m:k, and statements there may be one or more are carried out for each of these values. This value is called the iteration or trip count. Note that if the iteration count is negative, the loop is not executed.

It is basically a counter. In fact, if the index does appear explicitly in statements, the for can often be vectorized more details on this are given in Section 2. A simple example of a more efficient faster program is as follows. In this case i is assigned as a vector hence, this change vectorizes the original program. You may have noticed that the Editor does this for you auto- matically with a feature called smart indenting. If you leave them out you will get an error message. Nothing will happen until you do so.

The index moves through each element of the vector in turn, providing a neat way of processing each item in a list. Other forms of the for loop as well as the while loop will be discussed in Chapter 8. There are situations where a for loop is essential, as in many of the examples in this section so far. If you have written a for loop that involves the index of the loop in an expression, it may be possible to vectorize the expression, making use of array operations where necessary, as the following examples show.

Thus, t0 records when the calculation starts. The function etime returns the time in seconds elapsed between its two argu- ments, which must be vectors as returned by clock.

On a Pentium II, it returned about 3. If you have a faster PC, it should take less time. Now try to vectorize this calculation before looking at the solution.



0コメント

  • 1000 / 1000