# PDF Essential MATLAB for Engineers and Scientists

A single zero element in a vector or matrix renders it false. Exercises The following statements all assign logical expressions to the variable x. Did you get item f? The value 1 for true is therefore assigned to x. What about g? Try other values, including 0 and some negative values. Most banks offer differential interest rates. The Random Bank goes one step further and gives you a random amount in your account to start with! If condition is true, statementsA are executed, but if condition is false, statementsB are executed.

Commas or semicolons are essential between the various clauses. In general, the elseif clause is used: if. It works as follows: 1. If it is true, statementsB are executed, followed by the statement after end. In this way, all conditions are tested until a true one is found. If none of the conditions is true, statements after else are executed.

Arrange the logic so that not more than one of the conditions is true. There can be any number of elseifs, but at most one else. It is good programming style to indent each group of statements as shown. For example, the quadratic equation. Note the double equal sign in the test for equality; see Chapter 5 for more on logical operators.

This saves a lot of computing time and is easier to read if the if construct is in a loop that is repeated often. When designing the logic, you need to make sure that one and only one of the conditions will be true at any one time. However, whatever the value of bal, this condition will always be true. Can you see why? This is called nesting and should not be confused with the elseif ladder. You have to be careful with elses. In general, else belongs to the most recent if that has not been ended. The correct positioning of end is therefore very important, as the next example demonstrates.

Suppose you want to compute the solution to a quadratic equation. Your program could contain the following nested ifs The result is that else belongs to the first if instead of to the second one. Division by zero is therefore guaranteed instead of prevented! You may be wondering if for statements enclosing ifs can be vectorized. The answer is yes, courtesy of logical arrays. Discussion of this rather interesting topic is postponed until Chapter 5. In this example it is used to decide whether a random integer is 1, 2, or 3 see Section 5. If you are not familiar with complex numbers, you can safely skip this section.

However, it is useful to know what they are since the square root of a negative number may come up as a mistake if you are trying to work only with real numbers. The imaginary part of a complex number may also be entered without an asterisk, 3i. Some functions are specific to complex numbers. If z is a complex number, real z , imag z , conj z , and abs z all have the obvious meanings. It can be accessed through the Help button? A MATLAB program can be written in the Editor and cut and pasted to the Command Window or it can be executed from the editor by clicking the green right arrow in the toolbar at the top of the Editor window.

In other words, it is a program. The statements are carried out when the script file name is entered at the prompt in the Command Window. A script file name must have the. Script files are therefore also called M-files. The recommended way to run a script is from the Current Directory browser. The output from the script will then appear in the Command Window. A variable name consists only of letters, digits, and underscores, and must start with a letter. Only the first 63 characters are significant. All variables created during a session remain in the workspace until removed with clear. The command who lists the variables in the workspace; whos gives their sizes.

Clicking a variable in it invokes the Array Editor, which may be used to view and change variable values. Vectors and matrices are entered in square brackets. Elements are separated by spaces or commas. Rows are separated by semicolons. The colon operator is used to generate vectors, with elements increasing decreasing by regular increments decrements. Vectors are row vectors by default. An element of a vector is referred to by a subscript in parentheses.

• CHEAT SHEET?
• Regenerated Cellulose Fibres (Woodhead Fibre Series).
• Essential MATLAB for Engineers and Scientists?

A subscript may itself be a vector. Subscripts always start at 1. The diary command copies everything that subsequently appears in the Command Window to the specified text file until the command diary off is given. Statements on the same line may be separated by commas or semicolons.

## Essential MATLAB for Engineers and Scientists | Angus & Robertson

A statement may be continued to the next line with an ellipsis of at least three dots. Numbers may be represented in fixed-point decimal notation or in floatingpoint scientific notation. The default numeric type is double precision. All mathematical operations are carried out in double precision.

They operate according to rules of precedence. An expression is a rule for evaluating a formula using numbers, operators, variables, and functions. A semicolon after an expression suppresses display of its value. Array operations are element by element between vectors or between scalars and vectors.

The array operations of multiplication, right and left division, and exponentiation are indicated by. They may be used to evaluate a formula repeatedly for some or all of the elements of a vector. This is called vectorization of the formula. The format command controls the way output is displayed. When vectors are displayed, a common scale factor is used if the elements are very large or very small, or differ greatly in magnitude. The for statement is used to repeat a group of statements a fixed number of times. If the index of a for statement is used in the expression being repeated, the expression can often be vectorized, saving a great deal of computing time.

Any ex-. Any other value is true. The elseif ladder is a good way to choose between a number of options, only one of which should be true at a time. A string is a collection of characters enclosed in apostrophes. The volume of a tank is given as 2 gallons and 4 pints.

### Knovel offers following tools to help you find materials and properties data

Write a script that inputs this volume in gallons and pints and converts it to liters. Answer: Write some helpful headings so that your output looks something like this: Distance Now try to add tangents in the fourth column. Try some variations of the format command. Answer: 10, 2. The marks are out of Write a statement to find and display the average mark. Try it on the following: 5. Hint: Use the mean function. Can you do even better by vectorizing the code?

Can you figure out what it is? Now rewrite the script using vectors and array operations. Draw up a table of the values of i, j, and m to show how they change while the script executes. Check your answers by running the script. Compute the value of I. Answer: 0. Write a program that enters the following five consumptions into a vector and uses a for loop to calculate and display the total charge for each one: , , , , Write a program to compute and print the balance each month for a year.

Write a program that uses a for loop to compute the balance after a year of compounding interest in this way. Answer: Values in the last row of output should be 12, 0. Write a program to compute and display the population every ten years from to Try to plot a graph of the population against time as well Figure 9. Use the built-in function log for the natural logarithm ln. This chapter is an introduction to the design of computer programs. The topdown design process is elaborated to help you think about good problemsolving strategies as they relate to the design of procedures for using software like MATLAB.

This is a big advantage of MATLAB and tools like it ; it allows you to customize your working environment to meet your own needs. In the first part of this chapter we discuss the design process. In the second part we examine the structure plan—the detailed description of the algorithm to be implemented. We will consider relatively simple programs. However, the process described is intended to provide insight into what you will confront when you deal with more complex engineering, scientific, and mathematical problems during the later years of your formal education, your life-long learning, and your continuing professional education.

In the third part we introduce the basic construct of a MATLAB function to help you develop more sophisticated programs. To be sure, the examples examined so far have been logically simple. In other words, you have to develop a systematic procedure or algorithm for solving it. There are a number of methods that may assist in algorithm development.

In this chapter we look at one, the structure plan. There are numerous toolboxes available through MathWorks among others on a variety of engineering and scientific topics. A great example is the Aerospace Toolbox, which provides reference standards, environmental models, and aerodynamic coefficients importing for advanced aerospace engineering designs. In your working directory, e. Certainly, you want to be sure that the tools you save are reasonably well written i. What does it mean to create well-written programs? The goals in designing a software tool are that it works, it can easily be read and understood, and, hence, it can be systematically modified when required.

For programs to work well they must satisfy the requirements associated with the problem or class of problems they are intended to solve. The specifications i. That is, all options should be usable without error within the limits of the specifications see Figures 3. The program must be readable and hence clearly understandable. Thus, it is useful to decompose major tasks or the main program into subtasks or subprograms that do specific parts of it.

Each subtask should be designed so that it can be evaluated independently before it is implemented in the larger scheme of things i. A well written code, when it works, is much more easily evaluated in the testing phase of the design process. If changes are necessary to correct sign mistakes and the like, they can be easily implemented. One thing to keep in mind when you add comments to describe the process programmed is this: Add enough comments and references so that a year from the time you write the program. Note that the first few comment lines in a script file are displayed in the Command Window when you type help followed by the name of your file file naming is also an art.

The design process1 is outlined next. The steps may be listed as follows: Step 1 Problem analysis. The context of the proposed investigation must be established to provide the proper motivation for the design of a computer program. The designer must fully recognize the need and must develop an understanding of the nature of the problem to be solved. Step 2 Problem statement. Develop a detailed statement of the mathematical problem to be solved with a computer program.

Step 3 Processing scheme. Define the inputs required and the outputs to be produced by the program. Step 4 Algorithm. Design the step-by-step procedure in a top-down process that decomposes the overall problem into subordinate problems. The subtasks to solve the latter are refined by designing an itemized list of steps to be programmed. This list of tasks is the structure plan and is written in pseudocode i. The goal is a plan that is understandable and easily translated into a computer language. Step 5 Program algorithm. Translate or convert the algorithm into a computer language e.

Step 6 Evaluation. Test all of the options and conduct a validation study of the program. For example, compare results with other programs that do similar tasks, compare with experimental data if appropriate, and compare 1. The objective is to determine that the subtasks and the overall program are correct and accurate. The additional debugging in this step is to find and correct logical errors e. Step 7 Application. Solve the problems the program was designed to solve. If the program is well designed and useful, it can be saved in your working directory i. Step 1.

Let us consider the projectile problem examined in first-semester physics. It is assumed that engineering and science students understand this problem if it is not familiar to you, find a physics text that describes it or search the Web; the formulas that apply will be provided in step 2. In this example we want to calculate the flight of a projectile e. We want to determine the trajectory of the flight path and the horizontal distance the projectile or object travels before it hits the ground. Let us assume zero air resistance and a constant gravitational force acting on the object in the opposite direction of the vertical distance from the ground.

We want to determine the time it takes the projectile, from the start of motion, to hit the ground, the horizontal distance traveled, and the shape of the trajectory. In addition, we want to plot the speed of the projectile versus the angular direction of this vector.

We need, of course, the theory or mathematical expressions that describes the solution to the zero-resistance projectile problem in order to develop an algorithm to obtain solutions to it. Step 2. The mathematical formulas that describe the solution to the projectile problem are provided in this step. Then the maximum values of the altitude and the range are computed along with their respective arrival times. We must keep in mind when we study the solutions based on these formulas that the air resistance was assumed negligible and the gravitational acceleration was assumed constant.

Step 3. The outputs are the range and time of flight, the maximum altitude and the time it is reached, and the shape of the trajectory in graphical form.

Steps 4 and 5. The algorithm and structure plan developed to solve this problem are given next as a MATLAB program, because it is relatively straightforward and the translation to MATLAB is well commented with details of the approach applied to its solution i. This plan, and M-file, of course, is the summary of the results developed by. There are more explicit examples of structure plans for your review and investigation in the next section of this chapter. Keep in mind that it was not difficult to enumerate a list of steps associated with the general design process, that is, the technical problem solving.

However, it is certainly not so easy to implement the steps because they draw heavily on your technical-solution design experience. Hence, we must begin by studying the design of relatively simple programs like the one described in this section. Define the input variables. Calculate the range and duration of the flight. Compute the trajectory. Display in the Command Window and on figures the ouput.

Steps 6 and 7. The program was evaluated by executing a number of values of the launch angle and launch speed within the required specifications. The angle of 45 degrees was checked to determine that the maximum range occurred at this angle for all specified launch speeds. This is well known for the zero air resistance case in a constant g force field. How can you find additional examples of MATLAB programs good ones or otherwise to help develop tools to solve your own problems?

There are also many examples of useful scripts that are placed on the Web for anyone interested in them. This responsibility holds for all tools applied by the engineer and the scientist. Hence, it is very important just as in using a laboratory apparatus that users prove to themselves that the tool they are using is indeed valid for the problem they are trying to solve. To check that it works, type each line in the Command Window followed by Enter. Note the position of each graphic; location is determined by the three integers in the subplot function list of arguments.

Search Help via the question mark? A function M-file is similar to a script file in that it also has a. However, a function M-file differs from a script file in that a function M-file communicates with the MATLAB workspace only through specially designated input and output arguments. Functions are indispensable tools when it comes to breaking a problem down into manageable logical pieces.

Short mathematical functions may be written as one-line inline objects. This capability is illustrated by example in the next subsection. Further details on writing functions are provided in Chapter 4. The variable t in the inline definition of h is the input argument. You can create functions of more than one argument with inline. The construction of a function file starts with the. This is followed by the formula that is the function of interest that you wish to substitute a particular value of x to get the corresponding value of y. The structure plan for the evaluation of a particular algebraic function is as follows: 1.

It was saved as f. After saving it, it was used as follows in the Command Window. We want the determine the two roots of this equation, i. One way of dealing with this problem is to apply the known solutions of the quadratic equation. Start 2. Input data a, b, c 3. It is a useful exercise to test all possibilities to evaluate whether or not this function successfully deals with all quadratic equations with constant coefficients.

The purpose of this example was to illustrate how to construct a function file. Note that the only variables in the Workspace are the coefficients a b c. The variables defined and needed in the function are not included in the Workspace. Hence, functions do not clutter the Workspace with the variables only needed in the function itself to execute the commands within it. An algorithm is a systematic logical procedure for solving a problem. A structure plan is a representation of an algorithm in pseudo-code. A function M-file is a script file designed to handle a particular task that may be activated invoked whenever needed.

Carry out the plan by sketching the construction: 1.

## Essential MATLAB for Engineers and Scientists - Brian D. Hahn & Daniel T. Valentine

Draw two perpendicular x- and y-axes 2. Draw the points A 10, 0 and B 0, 1 3. While A does not coincide with the origin repeat: Draw a straight line joining A and B Move A one unit to the left along the x-axis Move B one unit up on the y-axis 4. Stop 3. Display M 4. Stop a Work through the structure plan, sketching the contents of M and N during execution.

Give the output. Test it on the data in Exercise 2. Use the structure plan in Section 3. Your script should be able to handle all possible values of the data a, b, and c. Adjust your script so that it can also find complex roots. Your algorithm must be able to handle all possible situations; that is, lines intersecting, parallel, or coincident. However, it is good for the development of your programming skills to do it the long way, as in this exercise. Plot y versus t for t from 0 to 10 in increments of 0.

Hint: Develop a solution procedure by working backwards through the problem statement. Starting at the end of the problem statement, the solution procedure requires the programmer to assign the input variables first followed by the execution of the formula for the amplitude and ending with the output in graphical form. This shape is called a uniform catenary. At this point you should be able to write a MATLAB program which inputs data, performs simple arithmetic operations on the data, perhaps involving loops and decisions, and displays the results of the computation in a comprehensible form.

However, more interesting problems in science and engineering are likely to involve special mathematical functions like sines, cosines, logarithms, etc. In addition, you may wish to import data to be plotted or operated on mathematically, and export data for future use. It also discusses the exporting of data to files in your work directory for later use with MATLAB or with other software tools. A short list of some of the more common ones follows. Use helpwin at the command line to see a list of categories of functions, with links to descriptions of the functions.

Note that if the argument of a function is an array, the function is applied element by element to all the values in the array, e. Since this text is written in a tutorial style, it is expected that you will examine the following list of some of the more common functions in MATLAB. It is also, to some extent, expected that you already know, from your first courses in mathematics and science, something about these functions.

One way to examine these functions is to plot them. For example, do the following exercise for all functions of the assigned variable x, as illustrated next. Note how the hours, minutes and seconds are left-filled with zeros if necessary. Let us consider the arc-cosine, the arc-sine and the arc-tangent functions, i.

If you specify x, i. To provide. The graphical comparison of the computed results is illustrated in Figure 4. Valentine - September The process of moving data between MATLAB and disk files is called importing from disk files and exporting to disk files. Data are saved in disk files in one of two formats: text or binary. Binary format is more efficient in terms of storage space required. Delimiters are the characters used to separate the data values in the file—spaces by default. You can use tabs instead of spaces by specifying the -tabs qualifier instead of -ascii.

If you save character arrays strings in this way, the ASCII codes of the characters are written to the file. The load command is the reverse of save, but has a curious twist. If the array A has been saved in myData. You can create it in a text editor, or it could be created by any other program that exports data in ASCII format. The command save filename x y z saves the variables x, y and z in the file filename.

If no variables are listed the entire workspace is saved. The extension. Seek help for all the save options. MATLAB functions may be used to perform a variety of mathematical, trigonometric and other operations. Write a script to input a length in meters which may have a decimal part and convert it to yards, feet and inches. Check: 3.

Section 2. The program displays every member xn computed. Adjust it to display only every 10th value of xn. Hint: the expression rem n, 10 will be zero only when n is an exact multiple of Use this in an if statement to display every tenth value of xn. Write a script which inputs a number of minutes and converts it to hours and minutes. Now write a script to convert seconds into hours, minutes and seconds. Try out your script on 10 seconds, which should convert to 2 hours 46 minutes and 40 seconds.

Design an algorithm i. The plan must specify the number and type of all notes and coins in the change, and should in all cases give as few notes and coins as possible. If you are not familiar with dollars and cents, use your own monetary system. It carries a uniformly distributed load of W per unit length, and there is a tension T along the x-axis. The topic is so useful and, hence, important that it deserves a chapter of its own.

Try these exercises on the command line: 1. If you correctly left out the semi-colon after the second statement you will have noticed that it returned the value 0. It should return the value 1. Discontinuous graphs Logical operators Subscripting with logical vectors Logical vectors instead of elseif ladders Can you see how to interpret this result?

Can you see why 0 0 0 1 0 is returned? When a vector is involved in a logical expression, the comparison is carried out element by element as in an arithmetic operation. If the comparison is true for a particular element of the vector, the resulting vector, which is called a logical vector, has a 1 in the corresponding position; otherwise it has a 0. The same applies to logical expressions involving matrices.

You can also compare vectors with vectors in logical expressions. The following script plots the graph, shown in Figure 5. Element-by-element multiplication by y with. A neat way around this problem is to use a logical vector to replace the zero with eps. If you are not too hot at trig graphs, perhaps you should sketch the graph roughly with pen and paper before you run the script! The scale on the MATLAB plot is therefore very large about , making it impossible to see the structure of the graph anywhere else.

The graph thus goes through zero at these points, which incidentally draws nearly vertical asymptotes for you. The function rand returns a pseudo- random number in the interval [0, 1 ; rand 1, n returns a row vector of n such numbers. Work out the following problem on the command line: 1. Now use a similar statement to count how many elements of r are greater than or equal to 0.

Since rand generates uniformly distributed random numbers, you would expect the number of random numbers which are less than 0. Generate a vector of a few thousand random numbers suppress display with a semi-colon this time and use a logical vector to count how many are less than 0. Repeat a few times with a new set of random numbers each time. Because the numbers are random, you should never get quite the same answer each time.

Without logical vectors this problem is a little more involved. Compare times for the two methods on your computer. Discarding the decimal part of this expression with floor gives an integer in the required range.

## Essential MATLAB for Engineers and Scientists - Brian D. Hahn & Daniel T. Valentine

Verify your result by displaying d. Estimate the probability of throwing a six by dividing the number of sixes thrown by Using random numbers like this to mimic a real situation based on chance is called simulation. Repeat with more random numbers in the vector d. The more you have, the closer the proportion of sixes gets to the theoretical expected value of 0. Can you see why it would be incorrect to use round instead of floor? The problem is that round rounds in both directions, whereas floor rounds everything down.

Table 5. The OR operator is technically an inclusive OR, because it is true when either or both of its operands are true. See Help on ops. The precedence levels of the logical operators, among others, are shown in Table 5. As usual, precedences may be overridden with brackets, e. If you have got this far you deserve to be let into a secret. MATLAB is based on the notorious language C, which allows you to mix different types of operators in this way Pascal, for example, would never allow such flexibility!

The explanation is due partly to the resolution of surprise a. The complete operator precedence is given in Table 5. Brackets always have the highest precedence. It simply churns through the expression according to its rules which may not be what you expect. Suppose r has the value 0. Staff Pick.

MATLAB RANDOM MEAN MEDIAN SYSMS-10

The Dutch House. How Powerful We Are. Macca's Makeover. Australian Pocket Oxford Dictionary. Rowling David Walliams. Fiction Non Fiction. Home Gardening International Subscriptions. Health Fitness International Subscriptions. Kids Girls. Would you like to rate and review this book? Add a Review Maybe Later. Valentine Subscribe to alerts Get information about new releases for these contributors straight to your inbox. Brian Hahn Daniel T. Be the first to write a review. This item qualifies for FREE delivery. Buy Now. In Stock Days In stock in our Sydney warehouse. Delivered in working days for most Australian capitals with online tracking.

Please allow additional time for WA, NT or regional areas. Vectors as Arrays and other Data Structures Dynamical Systems Simulation Introduction to Numerical Methods Signal Processing Symbolics Toolbox Complex Variables Applications. See All Customer Reviews. Shop Textbooks. Read an excerpt of this book!