Sunteți pe pagina 1din 119

PRACTICAL PROGRAMMING FOR ENGINEERS

Sergio E. Perez Copyright, Sergio E. Perez, 2005. No part of this document may be reproduced in any way without the authors consent.

Introduction: Every computer book written for engineers describes how important computing is to engineering, and rightly so. However, this important conclusion is seriously undermined when authors use examples that seem to have a tenuous connection to engineering reality. Open a computing book for engineers and you will likely see example problems such as determining leap years, or perhaps determining the distance a randomly walking drunk will cover interesting perhaps, but not really illustrative of the types of problems engineers are likely to encounter. This book introduces the reader to the practical aspects of computing using real engineering principles and problems from thermodynamics, heat transfer, fluid mechanics statics/dynamics, and strength of materials. This book is written assuming no knowledge of engineering or computing on the part of the reader, and should be used as early as possible in an engineering curriculum. Readers should be familiar with very basic calculus: differentiation and basic integration. If the authors achieved their goal, using this book will greatly simplify and enrich the study of engineering in the sophomore, junior and senior years. The book first quickly covers some of the basic features of Excel. While not originally intended as an engineering tool, Excel is very widely used in engineering as well as business, and is quite powerful. Some engineering texts come with software known as EES (Engineering Equation Solver). This software is extremely useful for solving the types of problems you will run into in engineering, and the authors believe should be part of any engineers tool box. Chapters II and III cover the use of EES using some real-world engineering problems.

Matlab is covered in Chapter IV, and is probably the most powerful engineering software available (Please bear in mind that engineering software is different from programming languages such as C++, FORTRAN and Java) certainly it is becoming the most popular. Why use Matlab if EES is available? You will see that Matlab can do much more than EES (but you will also see that for some applications EES is better!). And finally, last chapter covers some of the basics of Java, C++ and FORTRAN programming languages that students may run into in their careers. As a closing remark, the authors would like to point out that this textbook covers only the basics of Excel, EES, and Matlab that you may need to solve engineering problems. You will not learn how to highlight cells in different colors in Excel, nor learn about some of the more abstruse methods of matrix inversion using Matlab. Much of this information is available from the manuals available with the software. However, we feel that if you conscientiously work your way through this book, you will be able to solve many basic

engineering problems with considerably less effort than without it, and you will have a very solid programming foundation on which to build. To use this book you should have the following on your computers: Excel, EES (a trial version may be downloaded from www.fchart.com), and Matlab.

Chapter 1.

How computers work.


It seems magical if you think about it, but computers can perform hundreds of thousands of operations in the time it takes you to blink your eyes - millions of operations per second. They can store huge amounts of information and access that information almost instantly. How does a computer do it? Central to the operation of computers is the binary numbering system. We use a base ten numbering system in everyday life, which has repeating cycles of ten a number is carried over every 10th number. Ten distinct numbers are used (0-9). In the binary system there are repeating cycles of two numbers (0 and 1), and a number is carried over every two numbers. Two distinct numbers are used (0-1). The table below shows this more clearly. Base Ten 0 1 2 3 4 5 6 7 8 9 10 Binary (Base Two) 0 1 10 Number carried over 11 100 Number carried over 101 110 Number carried over 111 1000 Number carried over 1001 1010 Number carried over

Number Carried over The binary digits are referred to as bits (short for binary digits). Eight bits refers to a binary number such as 10010111, which has eight binary digits. A collection of eight bits is referred to as a byte. The first personal computers were 16-bit machines; they could work with binary numbers up to sixteen bits in length. With 16 bits, the largest decimal number that can be expressed is 65,536. If these computers needed to work with larger numbers, they first needed to break the numbers up into smaller components, perform operations on each of the components, and recombine them for a final answer. This is a relatively slow process. Todays personal computers are 32-bit machines. By using 32 digits, they can work directly with numbers as large as 4,294,967,296. The ability to work with 32 digits at a time makes these computers much faster than their predecessors.

At this point, the binary system may seem like an unnecessary complication. However, the binary system becomes very convenient for expressing numbers using On and Off pulses, which is very convenient using electronics. The On condition refers to the number 1, while Off refers to the number zero. To the computer, a voltage less than 2.5 is off, while a voltage greater than 2.5 is on. For example, say you had 8 current sources, each representing a bit (or digit). By having the sources read off, off, off, off, off, on, on, on you would express the binary number 00000111, or 7 in decimal. A computer can shut a switch on and off extremely fast using transistors much, much faster than you could ever hope to do by mechanical means (in fact, before transistors, computers used mechanical switches to send binary signals). It then becomes possible to very quickly turn current on-and-off, and thus express numbers using electrical signals. Transistors are made using semi-conducting materials such as silicon, which is extremely common in nature. Semi-conductors are neither conductors nor insulators they conduct electricity better than insulators but not as well as conductors. The semi-conductors are crystals (atoms bonded in repeating patterns) of silicon that are doped or mixed with small amounts of impurities. By properly selecting the type of impurity its possible to have an N type of semi-conductor (with extra electrons) or a P type semi-conductor (with missing electrons). Transistors are made by making a sandwich of N-P-N or P-N-P semi-conductors, as shown below. The result is a very useful combination that allows extremely fast on-andoff switching of current.

Base

Collector Emitter P N P

Note that three wires are connected into the transistor: the emitter, the base, and the collector. The remarkable thing about this arrangement is that current will flow from the emitter to the collector only if a small current enters through the base. In other words, we have an inexpensive way to turn current on and off by letting current flow into the base. Unlike mechanical devices which possess considerable inertia, the switching using transistors is as fast as the moving electrons. Before transistors, the same switching was done using tubes about half the size of a drinking glass. Tubes created considerable heat, consumed large amounts of power, and had a tendency to burn out frequently. They were used in the original computers for calculations for the Manhattan project during World War II, and required large rooms to house them. In contrast, transistors can now be miniaturized using integrated circuits so that millions of them are placed on a personal computers postage-stamp-sized processing chip (the brains of the computer). Before tubes, computers were made using mechanical switches to cycle on-and-off signals glacial speeds compared to transistors! The transistors switch current on and off at blinding speed, and perform mathematical operations using Boolean gates. There are and many types of gates, and below we illustrate an AND gate using mechanical switches a and b.

lamp

battery

You will notice that the switches are connected in series. The lamp is the output. The number one is represented when the lamp is on, and the number zero when the lamp is off. We are using mechanical switches to make it easier to visualize opening and closing the circuit a modern computer would of course use transistors. Lets take a look at all of the possibilities for output, depending on whether the switches are on or off. If switch a is on and switch b is off, the result is 0. If switch b is on

and switch a is off, the result is also 0. If both switches are off, the result is again 0. The only time the result is 1 is if both switches are on. We can illustrate these results using a truth table, as shown below. The types of operation we are now performing are known as Boolean Logic, after mathematician George Boole who in the 1800s pioneered what is now known as Boolean algebra. AND gate truth table A 0 1 0 1 B 0 0 1 1 Output (lamp) 0 0 0 1

We can also connect transistors together so that the result is a XOR gate. The XOR gate has the following truth table: XOR gate truth table A 0 1 0 1 B 0 0 1 1 Output (lamp) 0 1 1 0

In words, for the lamp to come on either switch can be on. However, if both switches are on (or if both are off), the lamp will not come on. Now comes the amazing part: we can use the AND gat and the XOR gate to add two onebit numbers. We do this to illustrate how gates are used to add numbers inside your computer. The possibilities for adding two one-bit digits are: 0+0 = 00 0+1 = 01 1+0 = 01 1+1 = 10 If you look at the truth tables closely, you will see that XOR gate gives the values of the right-most digit in each operation, while the AND gate gives the values of the left-most digit! In other words, say we wanted to use our XOR/ AND combination to add 1 + 1, the AND gate gives 1 and the XOR gate gives 0. We combine the two results to give 10, or 2 in

decimal. We can do any combination of one bit addition using the XOR/AND combination. There are other gates such as OR, AND, NAND, and XNOR gates which can be used in conjunction with the AND and XOR gates to add larger numbers and to perform multiplication, division and subtraction, as well as other more complicated operations. We wont go into these, but the bottom line is that the truth table of these gates or combinations of them is the same as the results of adding numbers. To summarize the last few bits of information: a) We can perform binary mathematical operations using combinations of Boolean gates. The truth tables of gate combinations are the same as the results of the required operations. b) Performing these calculations requires turning switches on and off. This is accomplished very quickly using transistors. HARD DISK, RAM and the CPU You can see that ones and zeroes (on and off) are used by the computer to perform mathematical operations. In fact, all operations done by your computer are done by manipulating on and off pulses through gates. However, in addition to having the capability to perform operations, your computer has to remember what it has done, both in the short-term and the long-term. If you have ever tried to add two digit numbers in your head, you probably realize that the biggest obstacle to performing the operation is remembering results of previous steps. For example, if you are adding 93+25, its easy enough to add the 5 and the 3, but you have to remember the result of the first step when you move on to the next digit, as well as any digits to carry over. In addition, your computer can be asked to store results in the long-term you really do not want to have to lose that long document when you shut off your computer! Your computer stores information permanently in the hard disk magnetically, in much the same way that a tape recorder records sound. The hard disk consists of one or more platters, covered with a material that can be rapidly magnetized as either N or S (on or off!). Recording heads read or write to the disk, although they are not in physical contact with the platter. The platter spins very rapidly, just a few millionths of an inch from the heads. When your computer is turned off, the magnetic information remains on the disk, and can be later retrieved. The capacity of computers hard disks has been rapidly growing since the advent of the personal computer. Todays machines have greater than 2 gigabyte hard

drives. This means they can store over 2,000 million bytes of eight bits each, or 16,000 million on or off settings. The problem with storing information on the hard drive is that it takes a long time to extract information from it, as compared to the time it takes to make calculations. A modern personal computers processor can perform over one billion operations per second, but the hard drive can only be accessed at a much slower rate! This is where RAM, or random access memory steps in. Random access memory is where information is stored in the short-term. Information stored in RAM is lost when the computer is turned off or after a program stops. Unlike the hard disk, RAM stores information (ones and zeroes!) electronically inside millions of gates. There is no need to wait for the platter to spin to the right location over the heads; the information can be accessed much more rapidly about 200,000 times faster than the disk. When you run any program, such as Microsofts Excel or Word, the program is moved from the hard disk into RAM. This explains why older computers are often incapable of running newer software there is just not enough capacity to store the program in RAM. The central processing unit (or CPU) is the heart of your computer, where the calculations are carried out. When you say you have a 2 gigahertz processor, you are referring to the millions of transistors/gates inside your CPU that can perform 2,000 million operations or cycles (such as adding, subtracting) per second. The CPU is so fast that it makes RAM even seem slow. To prevent a bottle-neck of information at RAM, there is storage on the CPU chip referred to as the internal cache, which is much faster than RAM. This allows information to flow to and from the CPU at a much faster rate.

Chapter 2.

EXCEL
Excel is a spreadsheet marketed by Microsoft Corporation. For all the bad press that Microsoft has gotten as far as its business practices, Microsoft has made it a policy to hire the best programmers and engineers in the world, and its products reflect the quality of their employees. Excel is an extremely powerful and easy-to-use spreadsheet that has gained world-wide acceptance in all industries, including engineering. Excel is best suited for engineers when the level of calculations is not very sophisticated as much of engineering work can be. This is not to say that Excel cannot handle complicated calculations far from it. Excel can be programmed, and Add-on tools allow Fourier series analysis, Bessel functions, complex numbers, solving simultaneous equations and automatic data acquisition, among others. However, the other tools we will cover are really much better suited for the more difficult engineering applications. The power of Excel for engineering applications is best shown by example. 2-D plots and Curve-Fitting Example 1. Drag force on a submarine. Naval architects (ship and boat designers) are very concerned with how much force holds back the motion of a vessel moving through the water. Imagine that you were standing on the seashore and had to pull a boat to shore using a long rope. You can easily envision that it would take some force to do this. If you really think about it you would conclude that the faster you wanted the boat to move, the harder you would have to pull. The force that resists the motion of an object through a fluid (for engineers a fluid is a gas or a liquid) is called drag force. The vessels engines must provide enough thrust to overcome the drag force, just as your arms had to provide enough pull to move the boat. Lets suppose that an experiment yields the following results for drag force on a submarine moving underwater: Speed (ft/s) 5 10 20 40 Drag force (pounds) 1000 4000 16000 64000

Engineers always want to look at a plot or graph of results. Seeing results on a graph lets the engineer visually detect any trends or anomalies.

10

We will input the data into Excel by typing into the cells which you can easily distinguish when you first turn Excel on. Try it on your own! Notice that you can type in numbers or words. When you finish, you can save your plot and data by going to File/Save. Below is a screen-shot of what we have so far:

Notice that a cell can be identified by its letter coordinate and number coordinate for example, cell A5 has the number 40 in it, while B4 has 16000. We now wish to make a plot of the data, so we highlight the data by left-clicking on it and dragging the mouse to surround the data. Note that we only wish to highlight the data, and nothing else. :

11

We now tell Excel to plot the data by clicking on the Plot icon located in the toolbar at top:

You then select x-y scatter plot (there are many others), which will show the data points and connect them with smooth lines:

12

Click Next, which will give you the screenshot below. You can see your data are presented in graphical format (by the way, data is plural, although the singular appears to be gaining acceptance). You can now type in a title for the plot, as well as a title on the x and y axes. It is extremely important that you specify the units that are being used on each axis! A few months down the line you might need to revisit your plot and know exactly what was going on! In addition, if your plot is intended to be part of a report, YOU MUST SPECIFY THE UNITS on each axis so that anyone reading your report will know exactly what you are talking about.

13

For the title you might write Drag Force on a Submarine, Speed (ft/s) might be good for the x-axis, and Drag (lbf) is adequate for the y-axis. By clicking on the tabs seen at the top of the screenshot above you can further adjust your plot. -----------------------------------------------------------------------------------------------------------Homework #1 Become familiar with the axes, gridlines, legend and data labels commands in the tabs above. Know what they do and how to use them. You may wish to use the Help command in the toolbar. Click Next, and select to display the plot as an object in Sheet 1 (the name Excel automatically gives to the spreadsheet you are working on), then Finish. The screenshot below shows the results so far.

14

Nice plot! You can print it by clicking on the plot outline (the border!) and going to Print in the toolbar. You can also copy the plot into a document by keying Ctrl + C to paste the document into the clipboard, and then by keying Ctrl+V into your document. Your plot probably has a Series 1 drawing on the right. This is for distinguishing between multiple plots on one graph, and was eliminated from this plot by right-clicking on Series 1 and deleting it. You may save the spreadsheet and plot by clicking on Save in the toolbar at top. Now we wish to do something extremely useful for engineers, which is to come up with an equation for the plot. In other words, we want a formula that gives us the drag force, given the speed. This is known as curve-fitting. Right-click on the graph line (the plot itself which Excel drew). Select Add Trendline. You will see several selections: linear, power, exponential, logarithmic, moving average and polynomial. Select Polynomial, 2nd order. Some examples of polynomials are: y = 5.67 x + 3.45 x + 1.1 x + 35 (a third degree polynomial) y = .45 x - 9.1 x + 3.9 (a second degree polynomial)
2 3 2

15

You can see that the general form of a polynomial of degree n is: y=ax +bx
n n-1

+ .. + c

Excel will then fit your data to an equation of the form you gave it.

16

Note the equation is printed on the plot. The equation is: y = 40 x 1E-11 x + 2E-10 The E refers to exponentiation: 1E-11 means 1 x 10 . Notice that this is an extremely small number compared to the data and the other numbers in the equation, as is the last 2 number. The equation may be written as y = 40 x . In other words, you now have an equation for y, given x. If you substitute into this equation a value of x of 20 the result will be 16,000. If you look at the plot carefully you will notice there appear to be two lines: a blue line and a darker black line. The lighter blue line is the original estimated best line through your data automatically drawn in by Excel. The black line is your fit to the data also automatically made by Excel by plugging many, many values of x into the equation you asked it to generate. Two words of caution here: a) We decided that the last two terms in the equation were insignificant, and rightly so. However, you should be careful when dropping terms, in that they may be significant if
-11 2

17

they are multiplied by large numbers. For example, an expression like 1E-5 x may seem small, but if x is very large, then the term may be significant. b) Be careful when using your equation beyond the range of the fitted data. In other words, the values of x that you gave Excel ranged from 5 to 40. If you then try to use the equation for values of x greater than 40 or less than 5, you may get unrealistic results, since the original experimental data never went outside of this range. Always look at your fit. Does the dark line appear faithful to the general trend of the data in other words, if you had to sketch in the values in-between your data points, would your sketch appear similar to the plot line drawn by Excel? If the plot line appears good, then you can conclude that you made a good selection when you selected a polynomial fit of 2nd order. If however, you are not satisfied with the way the plot looks, you can try a higher order, or even a different type of fit. In general, you should always use the smallest polynomial that represents the data well. However, you cannot expect too low an order to fit a complicated curve; a 1st degree polynomial does not curve (its just a straight line of form y = mx+b) , a 2nd degree polynomial curves once, a 3rd degree can curve twice you get the picture. Do keep in mind that to fit a second degree polynomial you need three data pair, a third degree requires four, etc. As mentioned above, the higher the order, the better you can get the fit to go through the data points. However, keep in mind that you may not want your fit to follow every single wiggle in the data particularly if the data are the result of an experiment where they may be some scatter in the data. Looking at the fit and visually determining if the fit is realistic is probably the best way to ensure you are not producing garbage! Occasionally, if you use too high an order for the polynomial, your fit will go through every single data point, but loop unrealistically in-between the data points. One of the problems deals with this very important issue.

-----------------------------------------------------------------------------------------------------------Homework/class activity: 1) Fit the data from the previous example to a 1st degree polynomial. What does the fit look like? Is it a good representation of the data? 2) Try a 3rd degree and fourth degree polynomials. Do they seem like good fits? What do you conclude about the coefficients in the equation? 3)What is the highest degree you could use for these data? 4) Try a power and a log fit to the data. What are the resulting equations, and do they appear to fit the data well? 5) Of all the fits you tried, which appears to be the best?

18

Mathematical Operations in Excel, Hierarchy of Operations, Unit Consistency, Integration by Curve-Fitting A gas expands inside a piston/cylinder arrangement, so that the piston moves up as the gas expands. The following pressure and volume readings are taken:
P (psia) 10 8 6 4 2 Vol (ft^3) 2 2.5 2.7 2.8 2.85

We wish to find the work done by the gas. From thermodynamics we know that the work done by a gas is given by the area under the P-V plot (that is, the work is the integral of PdV), so all we have to do is make a plot of the data and find the area under the curve. This becomes particularly easy if we make a polynomial fit to the data, and just do the integral. We plot the data and make a 3rd degree polynomial fit:
Chart Title 3

2.5

2 y = -0.0026x3 + 0.029x2 - 0.1315x + 3.02 R2 = 0.9993 1.5

0.5

0 0 2 4 6 8 10 12

Notice that the curve fit does not exactly go through all of the data points. Since there was probably some measurement errors in the experiment, we will not be too concerned with making sure every data point is exactly reproduced by the fit. Notice also that Excel is also giving us a R value. R is a number referred to as the 2 residuals, and is an indication of the quality of a fit. R can have values from 0 to 1, where 1 is the highest possible quality of the fit, hitting all the data points exactly. You 19
2

can make Excel show you the residuals by left-clicking on the fit curve, selecting Format Trendline/ Options/ Display R squared value on chart. The integration is now easily done due to the simple format of polynomials: W = PdV = .0026 x 4 / 4 + .029 x 3 / 3 .1315 x 2 + 3.02 x
V1 V2 2.85 2

The integral is evaluated by first substituting 2.85 into the formula, then substituting 2 into the formula, and then subtracting the second result from the first. We can use calculator to evaluate the integral, but lets let Excel do it. We go to any empty cell and click on it this is where the answer will be printed. We used cell D6. If you look up near the toolbar, you will see there is a white area with fx next to it (See below), known as the formula bar. This is where you will type in the formula for which you want an answer. YOU MUST START WITH AN EQUAL SIGN! Notice that we have put in the formula for the integral in a way that may look strange. The formula calls for evaluating the integral at x = 2.85 (the final volume) and at x = 2 (the initial volume), then taking the difference between the results. We decided to store the initial volume in cell D2, and the final volume in cell D1, and wrote the formula using D1 and D2 (see below!). Once you are finished typing in the formula into the formula bar, press the enter key in order to return to the spreadsheet. You raise a number to a power by using the ^ symbol. For example, 2 is 2^3. Multiplication is done using the asterisk symbol. For example, 2 x 3 is 2*3. Addition and subtraction are obviously + and -, while division is done using the / symbol. Nearly all major programming languages use this convention.
3

You can see that once you type in the initial and final volumes, Excel gives you the result in cell D6 (the cell in which you input the formula). We wrote the word answer in cell E6 for clarity. The answer appears to be about 2.39, but we are not really finished since we have to answer the question: in what units is the answer? This is such an important question, that

20

although not really part of an engineering computing course, it should be addressed here since it is such an important engineering issue. Since work is the integral of PdV, and P has units of lb/in^2, and volume has units of ft^3, then the solution units must be lb-ft^3/in^2. This is not a good situation since we are mixing inches and feet at any rate the resulting units do not look like anything we are used to seeing as far as work units! We then convert the lb/in^2 to lb/ft^2 by multiplying the answer by 144 ( there are 144 square inches per square foot). We can do this in two ways: by making a new cell with the right answer, or by modifying the formula. Lets do it by typing in a formula into cell D7. Check it out below all we are doing is telling Excel to multiply the result in D6 by 144:

The answer is now 344 ft-lb, which is a much more reasonable number as far as units are concerned. The second way of getting the proper answer is by altering the formula in D6. This is a pretty obvious idea, but it does open another very important item hierarchy of operations. This is a very fancy-sounding name for a simple concept. If you take a look again at our formula in cell D6, reproduced below, you might ask the question: how does Excel know which operation to do first? For example, take a look at the D1^4/4 term, which means the value in cell D1 raised to the 4th power, then divided by 4.

21

What if Excel had first divided the number 4 by 4, and then raised D1 to that number? Excel will not do this because there is a hierarchy or order of operations. In Excel and all of the software and languages we will study, operations are performed in the following order: Hierarchy of Operations First: anything in parentheses Second: exponentiation Third: multiplication or division (whichever it sees first from left to right) 4th: addition and subtraction (whichever it sees first from left to right). So, you can see that Excel would have known that D1 had to be first raised to the 4th power, then the result of that operation is divided by 4. If we now wish to multiply the entire result by 144, we simply add parentheses to the entire expression: one at the beginning, and one at the end: =(-0.0026*D1^4/4+ 0.029*D1^3/3 - 0.1315*D1^2/2 + 3.02*D1 - (0.0026*D2^4/4+ 0.029*D2^3/3 - 0.1315*D2^2/2 + 3.02*D2))*144 Note the previous expression (before multiplying by 144) had been: =-0.0026*D1^4/4+ 0.029*D1^3/3 - 0.1315*D1^2/2 + 3.02*D1 - (0.0026*D2^4/4+ 0.029*D2^3/3 - 0.1315*D2^2/2 + 3.02*D2) Homework Use a calculator to determine the result of the following operations. 1) 2^3/8+10/5 2) 3-8*2-(3*2) 3) 10-3/(8-6) 4) (10-3)/(8-6) 5) 10*3/5-6

Example 3: Tank Ullage Readings in a leaking oil tanker. (How a formula is automatically copied into other cells) An oil tanker is leaking oil from one of its tanks. The crew members measure the amount of oil in each tank by dipping a tape into the oil from above, and then measuring the distance from the top of the tank to the oil/air interface. These are known as ullage readings. We put the ullage readings into an Excel spreadsheet:
Tank 1 2 Ullage (ft) 2.1 2.7

22

3 4 5

4.6 2.6 2.7

We wish to know how much oil is remaining in each tank, in barrels. We are told by the barge operator that there are 32.2 barrels per inch in each tank, and that the top of the tanks is 25 feet from the bottom of the barge. In order to calculate the number of gallons in each tank, we must then subtract the ullage reading from 25 feet, and then multiply the result by 12 to get the inches of oil in each tank, then multiply by 32.2 to get the barrels remaining. Instead of doing this five times for each tank, we only need to do it once, then copy the result to other cells. The best way is by example! We first put the formula into cell C2 by again using the formula bar:

Next we highlight cell C2 by clicking on it, then press Ctrl + C to copy its contents to the computers clipboard. We then highlight cells C3 through C6 (by pressing Shift and moving down with the arrow key) and press Ctrl + V to paste. The result is almost amazing. Excel has copied the formula into each cell, but it has modified the formula so that the correct ullage reading is used. For example, for tank number 2, the formula must use the ullage reading in cell B3 instead of B2 (as appeared in the original formula), and Excel automatically changed it to read = (25 b3)*12*32.2. All of the other formulas are automatically changed as well. The values in each tank are then:
Tank 1 2 3 4 5 Ullage (ft) 2.1 2.7 4.6 2.6 2.7

8848.56 8616.72 7882.56 8655.36 8616.72

What if you do not want Excel to automatically change a formula? When you type in the formula you must tell Excel that the formula is constant by writing it as follows:

23

=(25 - $B$2)*12*32.2 In other words, by inserting the $ sign before and after the cell letter, we tell Excel to make the formula fixed. Average/Standard Deviation Example 4: Averages, Standard deviation You are trying to find the tension yield point of a composite material you have invented. The yield point is the point at which the material begins to deform very rapidly under a load. For example, if you put a small tension load on a sample material, it might stretch a small amount. If you continue to load the material it will continue stretching a small amount, until you reach a high enough load that the material begins stretching much more for the same amount of increase in the load. The material has reached its yield point, and if you were to remove the load, it would not return to its original length the deformation is permanent. Removing the load before the yield point is reached would result in the specimen returning to its original length. Below are some results for yield point of your specimen after ten trials. The specimen is circular, and measures 1.5 cm in diameter. The results are in newtons (by the way, a Newton is equivalent to about lb).
Trial 1 2 3 4 5 6 7 8 9 10 Yield (N) 5000 5010 4900 4980 5300 4920 5003 5010 4987 4870

We wish to know the average value of the yield point, which is extremely easy with Excel. The yield values are in cells B2 through B11. Go to any empty cell and type in the formula bar: = AVERAGE(B2:B11) The command tells Excel to take the average of cells B2 through B11:
Trial 1 Yield (N) 5000

24

2 3 4 5 6 7 8 9 10 average

5010 4900 4980 5300 4920 5003 5010 4987 4870 4998

However, the average is not enough when presenting the results of an experiment consisting of several trials. We are always interested in how consistent the data are in other words, do the results change significantly from one trial to the other? If they did you might conclude that your average must be looked at with great care. One way to judge the results of a test involving many results is through the standard deviation. The standard deviation is given by the formula:

You can think of the standard deviation as a measure of the average deviation of each trial from the average value of all the trials. Although it gives a value that is slightly different from average deviation, this is a good way to look at the standard deviation. To get the standard deviation of the data using Excel is simplicity itself. Just type into the formula bar for an empty cell: =stdev(b2:b11) Here is the result:
Trial 1 2 3 4 5 6 7 8 9 10 average s deviation Yield (N) 5000 5010 4900 4980 5300 4920 5003 5010 4987 4870 4998 117.3968

25

This deviation of 117.3968 must be compared in magnitude to the yield values. 117 out of the average of 4998 is roughly 2%. In other words, the data vary by an average of about 2% of the mean, which is probably an acceptable deviation (of course, this depends on your particular requirements). Incidentally, you could also take an average or a standard deviation going sideways (across a row). For example, say you wanted the standard deviation of the values in cells A2 to D2, you would simply type in: stdev(A2:D2) Solving Equations (Root-Finding) by Iteration Example 5: Solving an equation by iteration There are many equations which are unsolvable analytically. By analytically we mean using the usual algebraic techniques. However, equations may be solved numerically, which means by approximate methods. Approximate methods can be as accurate as you want them to be, as you will soon see. We dont have to search very far for an unsolvable equation. You may recall we came up with the equation for V as a function of P earlier: V =-0.0026*P^3+ 0.029*P^2 - 0.1315*P + 3.02 What if we were asked to solve for the pressure P, given a volume of 2.65? If you stare at the equation long enough you will soon see that its a tough one! It may be possible to solve analytically perhaps you have the time to contact someone in the mathematics department. However, it is pretty easy to solve this equation using Excel. Solving this equation is also known as root-finding, or finding out where the equation above crosses the zero point, if we move the V to the right hand-side: -0.0026*P^3+ 0.029*P^2 - 0.1315*P + 3.02 - V We will solve the equation in the original form. The procedure is simple: you guess values of P until V is equal to 2.65. All you need is a rough idea of where the answer is going to be, as there are probably three answers, since the equation is a cubic that is, it has a third power in it. An equation with a second power has two possible solutions, and one with an exponent to the 1st power has only one solution. You get the pattern. We go to Excel and type the formula into cell A1, making the P guess in D1. After a few tries we see the solution appears to be about 6.8:

26

This was a bit of work. We can automate the process by telling Excel to try values of P from 6. 7 to 6.9 in increments of, say 0.01. You can do this by typing the formula = 6.7 in cell A4, then in cell A5 typing in the formula = A4 + 0.01 . You would then copy this formula into 200 cells below, which you will remember will result in Excel appropriately changing the formula in each row. Dont worry about running out of rows. Excel allows 65,356 rows, and 256 columns! -------------------------------------------------------------------------------------------------------Homework: Finish the problem above, automatically coming up with an answer that is accurate to within 0.01. -------------------------------------------------------------------------------------------------------Problem: Solve the following equation for x if y = 4 using your computer, between 0 and -0.2.: 2 y = 3x + 14x 3 Do this automatically so Excel will try values from 0 to -0.2 in steps of -0.001. In other words, set up the formula in one cell, and copy it into many cells below it, trying values of x from 0 to -0.2. -------------------------------------------------------------------------------------------------------Trigonometric and Other Functions Excel calculates trigonometric functions with the following commands. Keep in mind that Excel takes angles in radians. There are 2 pi radians per 360 degrees, so you can convert from degrees to radians by multiplying by pi/180. Excel will recognize the number pi, but you must specify it as pi(): Tan(10* pi()/180) = tan of 10 degrees sin(2) = sin of 2 radians cos(2) = cos of 2 radians tan(5) = tangent of 5 radians OK you get the picture. For more trigonometric functions, please see the Help menu in Excel.

27

Other useful functions: exp(5) = e to the 5th power ln(5) = natural logarithm of 5 log(5) = base ten logarithm of 5 Homework: 1) Set up an Excel program that converts any number placed in cell b2 to radians. Display the number of radians, and the sine and cosine of the angle. 2) The tangential velocity of an object revolving about a point is given by: Vt = r , where is the rotational speed in radians/second, and r is the distance from the center of rotation to the point of rotation. Make an Excel program to give the tangential speed at values of r ranging from 0 to 10 m in increments of 1 m if the rotational speed is 10 revolutions per second.

Solving Ordinary Differential Equations by Eulers Method. Finite Differences. Finding the terminal speed of a falling object. Eulers method is a simple way to solve ordinary differential equations (ODEs). If you do not know what ODEs are, its very simple an ODE is an equation with a derivative in it with only one independent variable. The best way is to show an example. Lets say we know the drag force on an object as it moves through the air is 0.07 V^2 (in units of Newtons), where V is the velocity in meters/second. Drag force on objects moving fully immersed through fluids typically have this form of expression for the drag force, that is, some constant times the velocity squared. We wish to find the terminal velocity of the object if it is dropped from a high location and its weight is 500 N. When the object is first released, the object accelerates downward, pulled by gravitational force. The object accelerates until the drag force equals the weight of the object, at which point it falls at a constant speed. A diagram shows the direction of the forces:

28

0.07 V^2

500 N

We use Newtons 2nd law. We arbitrarily give the 500 N downward force a positive sign for its direction, and the upwards drag force of .07V^2 is given a negative sign:

F = ma
500 .07V ^ 2 = mdV / dt Note that we have replace the acceleration a by dV/dt. We now have a differential equation. If you have never seen one before, congratulations on your new-found discovery! A differential equation is just an equation with a derivative in it. Next we can approximate the dV/dt term by using finite differences, as follows:

dV / dt V / t = (V final Vinitial ) / t In words, dV/dt is approximated by the change in velocity over a time interval (which we will choose. This will give accurate results as long as the time interval is small. So, as a simpler example, if the drag force is 100, the mass is 100, the time interval is 0.1 s, and the speed at the beginning of the time interval is 1, we can solve for the final speed at the end of the 0.1 s:

F = ma = mdV / dT
500 100 = 100(V final 1) / 0.1 We can easily solve for the Vfinal at the end of the 0.1 s as 41.

29

In order to finish the problem we only need to keep marching forward in time so that the final velocity of one time step becomes the initial velocity for the next time step. The sample problem we just did was simpler than the actual problem we are doing, because the drag force is not a constant 100. The drag force is 0.07*V^2 in other words, the drag force depends on the velocity itself, which is what you are trying to find at each time step! The solution is to use the previous time steps velocity to calculate the drag force, and if your time steps are small enough you will not have significant errors. How do you know if your time step is small enough? If you repeat your calculations at a smaller time step, and you see no change in the solution, then you know you do not need to go any smaller time step! One thing to keep in mind when you are marching forward in time like this: if you make the time step too large your solution will blow up, in the sense that after a few time steps you will have an astronomically large result. In other words, if you make the time step large you will get inaccurate answers, but if you make it too large your solution will blow up. Lets set up the equations now. We want to have many increments of 0.1 seconds, which we could laboriously type into Excel. We are not sure how many yet, since we do not know how long it will take to reach terminal velocity, but lets do 1000 time steps and see if we reach a constant speed.

We re-write Newtons 2nd Law, inputting the expressions for the weight, drag force, and acceleration:

(500 .07 * V 2 ) = m(V final Vinitial ) / t


We solve for the velocity V at the end of the time step:

V final = (500 .07 * V 2 )t / m + Vinitial


We will march forward in time, using the previous time steps velocity to calculate the drag force 0.07 V^2. The mass m is 100 kg, and the time step is 0.1 s. Again, the previous time steps final velocity becomes the next time steps initial velocity. Lets do the first few time steps here so you can get a better idea of what is going on: Time V at end of time step 0 0

30

0.1 0.2 0.3

V final = (500 .07 * 0 2 )0.1 / 100 + 0 = 0.05 V final = (500 .07 * 0.052 )0.1 / 100 + 0.05 = 0.45 V final = (500 .07 * .452 )0.1 / 100 + .45

And so on. Programming this in Excel is pretty simple, since you only need to write the formula for one cell, then copy it to all the others. The mass is in cell D2, and the time step is in cell E2. We then put the following formula in cell B4, to the left of cell C4: =(500-0.07*B3^2)*$E$2/$D$2 + B3 Note that B3 is the velocity in the previous time step. We then copy the formula into the cells beneath it and we are finished. Excel automatically adjusts the formula so that the formula always uses the cell above it to calculate the drag force and the velocity at the beginning of the time step. A
time 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7

B
m/s 0 0.5 0.999983 1.499913 1.999755 2.499475 2.999038 3.498408 3.997551 4.496433 4.995018 5.493271 5.991159 6.488646 6.985699 7.482283 7.978364 8.473908

D
Mass 100

E
deltat(s) 0.1

Cell C4

The spreadsheet above only shows the first few time steps. It took about 700 time steps or about 70 s to reach the terminal velocity of 84.5 m/s. The end of the spreadsheet is shown

31

below, with the elapsed time on the left, and the velocity at right. You can see that the velocity is still increasing, but very slightly.
69.7 69.8 69.9 70 70.1 70.2 70.3 70.4 70.5 70.6 70.7 84.47292 84.47342 84.47392 84.47441 84.47489 84.47537 84.47585 84.47632 84.47678 84.47724 84.47769

Homework/Projects: 1) Use a time step of 0.05 s, and compare the velocity after 30 s with that obtained using 0.1 s. Keep in mind that you will have to take twice as many time steps to reach 30 s if the time step is half as big! Have your program print the elapsed time so that it is easy for you to compare the velocities, as in the spreadsheet above. What conclusion do you reach about the size of the time step? 2) Calculate the terminal velocity of a sphere floating from the bottom of the ocean. The spheres weight is 50 lb. Its volume is 1 cubic foot. The density of seawater is 64 lb per cubic foot, and the buoyant force on the sphere is equal to the weight of the displaced 2 fluid (64 lb). The drag force on the sphere is 0.3V . This problem is essentially the same as the previous one, but you must now include the additional force due to buoyancy. Also kep in mind that the mass must be divided by the gravitational constant 32.2 in order for F =ma to work properly. 3) A 40 kg rock is launched directly upwards at a speed of 3 m/s. If the drag force on the rock is 0.001 V^2, calculate the height reached by the rock. In this problem you must keep track of the total distance covered at each time step. When the velocity of the rock is zero (or about zero) you know you have reached the apogee.

SOLVING SIMULTANEOUS EQUATIONS


Dont use Excel, its like going from NY to NJ via California! But if you must, the discussion below will show you how. Excel has the capability to solve large sets of simultaneous equations. We will illustrate the technique by solving a heat transfer problem. We want to solve for the temperatures at the faces of the slab if it is exposed to moving air at either face, as shown by the diagram below. The slab has a uniform temperature on each face, and the air has temperatures of 30 and 90 F on the left and right faces. An oven wall at left has a temperature of 1000 R (to covert from F to Rankine, add 459):

32

T = 1000 R

T1

T2

Wind = 10 ft/s Tair = 90 F

Wind = 20 ft/s Tair = 30 F

You might ask yourself why T1 is not equal to the air temperature around it. The reason for this is that the wall is being cooled by the other face, which is exposed to 30 F air. In addition, the hot oven wall is radiating energy to the slab. the same way, T2 is not equal to the temperature of the surrounding air. There are three modes of heat transfer occurring in this case. Conduction is occurring through the solid slab. Conduction heat transfer is what happens when a solid is exposed to a temperature gradient (that is, a temperature difference). Convection is occurring on the right and left faces of the slab. Convection heat transfer is what occurs when you have a temperature gradient and a fluid is involved (recall a fluid is a liquid or a gas). Bottom line: if a fluid is involved, its convection. Radiation heat transfer is occurring between the slab and the hot oven wall. Radiation is energy emitted due to an objects temperature, and requires no medium the suns radiant energy reaches us through millions of miles of vacuum in space. Thermal radiation is not to be confused with nuclear radiation. The conduction heat transfer Q through the slab is given by the equation: Qcond = 100*(T1 T2) Please note the number 100 is a constant that only applies to this particular problem. The constant includes the thickness of the slab and the thermal conductivity of the slab. The convection heat transfer on the left wall is given by the equation: Qleft = 5* ( 90 T1)

33

Where T1 is the temperature of the left wall, and 90 is the air temperature to which the wall is exposed. The constant 5 is a constant particular to this problem only, and depends on the speed of the moving air. The convection heat transfer on the right wall is given by: Qright = 25* (T2-30) Notice this equation is very similar to the one before it. The constant is bigger because the air is moving faster over this face, thus increasing the rate of heat transfer. The order of the delta T term was changed to ensure all the terms are positive. The radiation heat transfer between the hot oven wall and the slab is (assuming that all of the heat leaving each object by radiation lands on the other): Q rad = 1.712E-9 * (Toven^4 T1^4) The 1.712E-9 is the Stefan-Bolzmann constant, which governs radiative heat transfer. Note that radiation depends on the wall temperatures to the 4th power it becomes very significant when temperatures get high! We can now make several statements which will give us our final simultaneous equations: The total heat flowing into the left wall is the sum of radiation plus convection, so: Qtotal = 1.712E-9 * (Toven^4 T1^4) + 5* ( 90 T1) [1]

The total heat going into the wall also flows through the wall by conduction, so: Qtotal = 100*(T1 T2) [2]

The total heat flowing through the slab equals the heat being convected at the right face: Qtotal = 25 *(T2 30) [3]

We then have three equations and three unknowns: Qtotal, T1, and T2. We re-arrange equations 1, 2, and 3 so that we have a constant on the left-hand-side of the equation: From equation 1: 1.712E-9 *Toven^4= Qtotal 5*(90-T1) +1.712E-9*T1^4 or 1176.2 = Qtotal 5*(90-T1) + 1.712E-9*(T1+459)^4 [1a]

34

Note that we have added 459 to T1 because we need the absolute temperature in Rankine. From equation 2: 100 = Qtotal/(T1-T2) From equation 3: 25 = Qtotal/(T2 30) [2a] [3a]

Now that we have a constant on one side of each of the equations, we can simultaneously solve [1a], [2a], and [3a] using Excel. We first input guesses for the unknowns qtotal, T1, and T2 into spreadsheet cells B7, B8, and B9. Next we input equations 1a, 2a, and 3a into cells B2, B3, and B4. Cell D2 has the oven temperature of 1000 R. A B
Equations 200.1123243 5 10 1 2 3 4 5

D
Oven 1000

qtotal t1 t2

Solutions/Initial Guesses 200 7 90 8 50 9

The three equations are: = 0.000000001712 *B8^4 + B7 - 5*(90-B8) =B7/(B8-B9) =B7/(B9 - 30) Now comes the tricky part. Go to Tools/Solver. If Solver does no appear, you can add it in by clicking on Tools/ Add-ins and selecting Solver (you may have to go to the original Excel CD). Once you are in Solver, you must do the following: 1) Pick a so-called target cell from one of your equations. We selected cell B2. 2) Specify what the value is on the left-hand side of the equation (remember we set each equation equal to a constant). In this case its 1176.2.

35

3) Specify where the unknowns and initial guesses are, which in our case is cells B7 through B9. 4) Specify the values of the left-hand sides of the remaining equations. This is done in the box labeled Subject to the Constraints.

Hit solve, and the answer should appear where your guesses were:
Equations 1176.2 99.99999986 25 Solutions/Initial Guesses 1180.873899 89.04369499 77.23495598 oven 1000

qtotal t1 t2

T1 is then 89 degrees F, while T2 is 77.2 F. That was a lot of work. We conclude the chapter on Excel with the conclusion that its very useful, but solving simultaneous equations is like digging a ditch with a spoon! Fortunately there are easier ways to do it.

36

Chapter 3: Engineering Equation Solver (EES)


EES is a program designed for solving engineering problems. It has five features that make it very attractive to engineers: 1) EES can solve simultaneous equations very easily much more easily than Excel. 2) EES can make publication-quality plots almost as well as Excel. It can also do 3-D plots. 3) EES makes it easy to perform parametric studies that is, showing the effect of varying specified values. 4) EES easily gives you properties of steam, air, refrigerants, and many common substances frequently encountered in engineering. 5) EES can be programmed in its own language that is similar to Pascal programming language. In this chapter we will explore each of these capabilities.

Solution of Simultaneous Equations.


In the previous chapter we used Excel to solve the equations below. Qtotal = 1.712E-9 * (1000^4 T1^4) + 5* ( 90 T1) Qtotal = 100*(T1 T2) Qtotal = 25 *(T2 30) Please consult the previous Excel portion on solving simultaneous equations for an explanation of what these equations are. Briefly, the 1000 is the temperature of an oven that is radiating heat to another wall next to it, separated by an air gap. The temperature of the air in the gap is 90, and T1 is the temperature of the wall facing the oven. T2 is the temperature of the opposing side of the wall, and 30 is the temperature of the air surrounding the opposite wall. In order to solve these equations, we must set each of them equal to one of the unknowns (T1, T2 and Qtotal). The first equation can remain as it is. The second equation is solved for T1: T1 = Qtotal/100 + T2 The third equation is solved for T2 T2 = Qtotal/25 + 30 [3] [2] [1]

37

Start the EES software and type in the three equations, one per line:

Note that we wrote First Example Problem on the first line. By using quotation marks, we can write comments anywhere in the program these comments do not get processed. This may seem like a trivial function now, but it is considered good programming practice to use comments liberally. Comments help you organize your program and can be a huge help after you write your program and revisit it. After you type in the equations, you must tell EES the approximate value of the solutions, just like you did with Excel. This is not because EES is poorly designed its possible that a system of equations has more than one solution, so you must tell the software the approximate values of the solution that you want. The unwanted solutions are usually unrealistic. From the problem we know that T1 will be about 90, T2 about 30 and Qtotal about 6000 (see the second equation above). EES will use these values as 1st guesses in a process that can be described as intelligent trial-and-error (in the computing section we will look at one technique for doing this). Unless you tell EES otherwise, it will search for solutions to the unknowns from negative infinity to positive infinity, starting with the initial guess you give it. This can lead to problems since EES stops after 100 iterations or trials at solving the equations (remember, its a trial-and-error process). This value is adjustable, but by default it is set to 100 iterations. Even if you did change the maximum number of trials, its possible that it could take EES a long time to come up with a solution, especially if you have very large numbers of equations. For the reason cited above, it is a good idea to give EES a range of where to look for solutions, as well as a good first guess.

38

In the problem above, we know that the coldest any temperature can be is 30 F (since this is the temperature of the cold air on the right wall), and the hottest it can be is 1000 Rankine or abut 540 F (this is the temperature of the oven). We are not sure of the maximum Qtotal, so we will leave the default range of infinity to + infinity. In summary of the last few paragraphs, we must specify some initial guesses for the unknowns, as well as ranges of the solutions. This is done by going to Options/Variable Info. The screen below will appear. You can see that we have entered the initial guesses as well as the limits:

Click the OK button, which will return you to the main screen, then hit F2 to run the program. A screen shows the computation time, the maximum residual, and the maximum variable change. The maximum residual is the maximum difference between the left-hand side of the equations and the right hand side. Recall that EES is using an educated trial-and-error process to solve the equations when the LHS and RHS of the equations come to within acceptable limits, EES considers the problem solved. In this case the maximum difference of the three equations is about 1E-10 pretty close! The maximum variable change refers to the maximum amount that the unknowns changed between the last iteration and the previous one. This change must be below a certain maximum. If not, EES considers the solution to be invalid, and will tell you. Click on Continue and your output is displayed:

39

That was much easier than Excel! Now comes another very useful feature of EES the ability to perform parametric studies. Lets say that we want to know the effect of changing the oven temp, currently set to 1000 in Equation [1] above, from a value of 500 to a value of 2000. We change the first equation by replacing the 1000 with the variable name toven. We did not have to use that particular name just about any other name will do, as long as it does not start with a number or its a reserved name. By reserved names we mean things like sin, cos or log that have pre-defined meanings for the computer. Since we are using larger values of toven, we should change the maximum expected temperature for T1 and T2 to about 2000. We decided to set the maximum value of qtotal to + infinity, just to keep life simple. Go to Tables/New Parametric Table. The screen below appears:

Click on toven and then Add. We have just instructed EES to vary values of toven. We are also specifying 10 values of toven. Click on T1 as well, then Add. Our table will then show T1 and toven values. Click OK.

40

A table will appear with columns showing T1 and toven. We want to vary the values of the oven temperature toven from 500 to 2000 R and examine the effects upon the wall left face temperature T1 We could input ten values into the table, but it can be done automatically by going to Tables/Alter Values. Select toven (the variable you wish to vary), then select the initial and final values of 500 and 2000 (you can pick the increments or the final value). Click Apply, then OK, and the ten table values of toven from 500 to 2000 will be automatically filled in, as shown below:

We now instruct EES to solve the equations using each value of toven on the table by pressing F3 (note that clicking F2 as you did before would not run the parametric study, but what is on your program screen). The screen below appears (note that your table number will be different):

41

Note that the Update guess values box is checked. This means that EES will use the previous toven results as guesses for the next toven calculation. Click OK. The screen below appears giving the results for each toven.

We can now easily plot this information. Go to Plots/New Plot Window/X-Y plot. A window appears in which you must select what to place on the x and y axes. You can fill

42

in a title, select the limits of the plot (which we are not changing from the default values), as well as place a legend on the plot. Press OK and the plot below appears:

We now have a very useful plot, showing that as the oven temperature is increased, the oven radiates heat to our wall, increasing wall temperature T1. We can also perform curve-fitting, just like with Excel. Once your plot is made, select Plot/Curve fit. A window will appear as below. Select the type of fit, and click Plot. The equation will come up in the box at the bottom, and you will be able to select whether you want the equation printed on your plot. In addition, you can choose to have the equation copied to the clipboard so that you can paste it into any document or program (by keying Ctrl + V) :

43

THERMOPHYSICAL PROPERTIES A very useful feature of EES is its ability to provide thermophysical properties. This is very important and convenient for doing thermodynamics problems. You are no-doubt aware that any substance, such as water, air, or a refrigerant flowing through an air conditioner has properties such as temperature, density, pressure, viscosity (there are others such as internal energy, specific heat, enthalpy, entropy and specific volume about which you will learn more in your thermodynamics class). It turns out that if you specify two properties, you can know all of the others. So, say you are given the density and the pressure of steam you can find the other properties such as temperature, temperature, enthalpy, specific heat and entropy by using thermodynamic tables. Or you can use EES, which is much easier. The reason EES is easier than using tables is that tables often need to be interpolated, since the table values may not be exactly the number you are looking for. For example, the table might give you pressures in increments of 50, but you need to read a value of, say 28.7. It then becomes a nuisance to use the tables, especially if you need to interpolate between two variables, say pressure and temperature. Lets do an example. Say that you have water at 412 F and P =12 psia (lbf/in^2 absolute), and you want to know its density, enthalpy and entropy. In EES, first go to Options/ Unit System. The screen below appears:

44

By default, EES uses SI units of kPa, K and kJ. We want to use the English system in this case, and we also want specific properties on a Mass basis (see the figure above). Specific properties on a mass basis are properties that are given to you per unit mass. For example, BTU/lb as opposed to BTU/mole. Dont worry about BTUs yet! Once you click on the English system, you will be able to choose Rankine or degrees F, as well as your pressure and energy units. Select degrees F and psia for the units. In the unit box you also have the capability to specify whether you will be using radians or degrees in any trigonometric calculations. Click OK, and you are back to the main screen. Type in the following commands: Demonstration of thermodynamic properties using EES Den = density(water, T=412, P = 12) What we have done now is instructed EES to find the density of water at the indicated pressure and temperature, and that we will call that density Den (incidentally, EES is not cap sensitive, in that Den and den and read by EES as the same thing) Press F2, and EES gives the result:

45

EES even gives you the units of the answer in the square brackets. Lets do the remaining properties by adding the commands: enthalpy =enthalpy(water, T=412, P= 12) entropy = entropy(water, T = 412, P=12) And lets say we also wanted to know the quality of the water. The term quality applies when you have an equilibrium mixture of steam and water vapor. For example, the steam exiting a turbine may be a mixture of liquid droplets mixed with steam. The quality refers to the mass fraction of vapor. If the quality is 0.7, then the mixture is 70% steam and 30% liquid water by mass. We can ask EES for the quality of the water: Quality = quality(water, T=412, P=12) Our output is:

You can see that the quality is 100 or 100% steam (you will usually see quality expressed from 0 to 1 in thermodynamics texts rather than on a percentage basis).

46

There are exceptions to the rule that you need to specify two properties in order to know all the others: the enthalpy h and internal energy u depend only on the temperature T if you are working with an ideal gas. An ideal gas is one that obeys the ideal gas law: PV = mRT. For example, to get the enthalpy of air at 300 K, just type into EES: en = enthalpy(air,t=300) When you press F2 you will see the result. EES will treat air as an ideal gas, and any gas whose name you call using a formula. For example, O2, N2 and CO2 get treated as ideal gases, while Oxygen, Nitrogen and CarbonDioxide do not (you must specify 2 properties for the latter). Dont stress is too much if you are giving too many properties when you call the properties functions, EES will let you know if you are using too many or too few. Here is a list of the substances for which EES can give you properties. Notice that there are columns for ideal gases and real fluids (non-ideal gases). This list came from the Help section of EES, under Functions and Properties/ Fluid Property Information:

47

In addition, the properties available are given by the chart below, taken also from the Help section, under Thermophysical Functions:

Notice that there are many more functions than we have spoken about. -------------------------------------------------------------------------------------------Problem 3-1: Find the density of air at 30 C and P = 101 KPa We first set the units to SI, Celsius, per mass, and P in KPa and write: Den = density(air,P=101, T =25) The answer is 1.16 kg/m^3 --------------------------------------------------------------------------------------------------------Problem 3-2 Find the enthalpy of nitrogen at P = 20 psia and T = 500 F. First (a) establish the phase, then, if gas, find the enthalpy assuming (b) ideal gas (c) real gas behavior (d) calculate the percent difference between the real and ideal gas values. Solution:
x= quality(nitrogen, T=400,P=20) hideal=enthalpy(n2, T=400) hreal = enthalpy(nitrogen,T=400,p=20) percentError = (hreal-hideal)/hreal * 100

48

The error is very low! ---------------------------------------------------------------------------------------------------------Problem 3-3: The definition of the constant pressure specific heat Cp is dh/dT (at constant pressure), where h is enthalpy and T is temperature. Approximate dh/dT as h / T , and calculate Cp at 500 F, by using enthalpy h values at 600 and 400 F. Then compare with the value given by EES. Calculate the percent error in the approximation. Solution:
h1 = enthalpy(h2o,T=400) h2 = enthalpy(h2o,T=600) cpreal = cp(h2o,T=500) cpcalc = (h2-h1)/200 error = (cpreal-cpcalc)/cpreal * 100 Discussion: -.025 % is very low. We can approximate any derivative using finite differences.

--------------------------------------------------------------------------------------------------------Important note regarding water properties: You may have noticed that EES gave you negative values for enthalpy of H2O (ideal gas). If you were to ask EES for the enthalpy of water (real fluid), it would give you a value thats positive and numerically very different! This is a bug in EES, but its actually OK because we are interested only in changes in enthalpy, say h2 h1. The change in enthalpy between two temperatures will be about the same whether you use the ideal gas or the real fluid property call - the absolute values are different, but we dont care about those (in fact, absolute values of enthalpy are meaningless). You only have to be careful if you are trying to compare the calculation of enthalpy between an ideal gas and a real fluid. This appears to be so only for water, but applies to entropy s and internal energy u as well. --------------------------------------------------------------------------------------------------------Problem 3-4: Calculate the change in enthalpy h for water at T = 400 F and P = 20 psia, to T = 500 and P = 20 psia two ways: a) by assuming the water vapor is an ideal gas b) by treating the water vapor as a real fluid. c) what are the enthalpy h values for the ideal and non-ideal cases. Do they seem the same? d) how do a and b compare? What do you conclude? --------------------------------------------------------------------------------------------------------Problem 3-5:

49

Perform a parametric study of the Cp of air as a function of temperature, from T = 20 C to T = 1000 C. Make a plot of Cp as a function of temperature. Make sure you set the units properly (generally speaking, always select your units on a per mass basis!). --------------------------------------------------------------------------------------------------------Problem 3-6 The work done through a turbine is: w = enthalpy in enthalpy out heat loss, or w = hin hout q. This is from the 1st law of thermodynamics for open systems. Assuming heat loss q is zero, and the inlet conditions into the turbine are: T = 1000 F, P = 1000 psia, and outlet conditions are: P = 15 psia; quality x = 0.99. Calculate the work done, in units of BTU per lbm of steam. -----------------------------------------------------------------------------------------------------------Problem 3-7 If a turbine is operating without losses of any kind (including heat and friction), then the entropy s2 coming out of the turbine is equal to the entropy s1 going into the turbine. Repeat problem 3-6, assuming ideal turbine operation (no losses). The exit conditions are now P = 15 psia, and S2 = s1 (we are no longer specifying the exit quality. Calculate the work done and the quality of the exit steam.
Solution 3-7: sin = entropy(water,P=1000,t=1000) hin = enthalpy(water, P=1000, t=1000) hout = enthalpy(water, p=15,s=sin) work = hin-hout x = quality(water,p=15,s=sin)

------------------------------------------------------------------------------------------------------------

We have only scratched the surface of the property functions available in EES. Use the Help section, once you know a little more thermodynamics, to become familiar with some of the other very useful functions.

50

Chapter 4. Programming in EES


This section serves as an introduction to programming as well as a specific primer on programming in EES. Once you know how to program in EES, you can easily learn how to program in Matlab, C++ or any other language, since many of the concepts are very similar. Tools such as looping, counters, subroutines, conditional statements and arrays are used by all of the languages we will study. Looping, counters, and subroutines/ Solving a differential equation using Eulers Method: Lets say that you wanted to do the operation of multiplying 0.1 by 1000. You can do this in your head easily and know the answer is 100. Lets say that for some reason you could not do multiplication and had to do this problem by addition. You could certainly solve the problem then by adding 0.1 1000 times, since by definition, this is what multiplication really is. This will take a long time! We can instruct computers to do this automatically for us with something called a program, or code. A program is just a series of step-by-step, very specific instructions for a computer to follow. Check out the following code using EES language, and see if you can figure out whats going on. All instructions in a program are performed in order, from top to bottom: inc = 0.1 we specify the adding increments, and call them inc call adder(inc: x,i) we call procedure we named adder, sending inc to it. adder will calculate x and i procedure adder(inc:x,i) here is procedure adder. Note the parentheses contents are same as when we called adder x=0 x first set to zero i=0 i set to zero repeat x = x + inc i=i+1 until (i>=1000) we start a loop here x will be incremented by 0.1 each loop i will be incremented by 0.1 each loop the loop will be repeated until i is greater than or equal to zero

end end of the procedure Lets look at what is happening, step-by-step: We first specify the increments we will be adding. Recall that we will be adding 0.1 1000 times, so 0.1 is the increment.

51

We will perform our calculations in a procedure, which is just a different and discrete part of the main program. EES only allows looping (which we will get to in a second) inside a procedure. Looping cannot be done in the main program using EES (this is not so in Matlab and C++) . In other languages, a procedure is called a subroutine. One way to think of the procedure is like a caterer. You give a caterer an order (inputs to the procedure) and the caterer does the work for you, returning your order (outputs from the procedure). The inputs to the procedure come first, followed by a colon, then the outputs of the procedure. The statement in our code: call adder(inc:x,i) tells EES that we are calling a procedure called adder (we could have called it just about anything we wanted!). The input to the procedure is the value of inc (which the computer knows is 0.1 because you told it so), and the procedure will calculate and return values of x and i. The statement Procedure adder(inc:x,i) specifies the beginning of the procedure. Notice that the arguments inside the parentheses are identical to the statement calling the procedure. x and i are first initialized to zero. This means they are given initial values of zero. The line reading repeat marks the beginning of the loop. A loop is a series of calculations or operations that are repeated. You specify how many times the loop is repeated in this case it will be 1000 times, but you will do this on another line. We begin the instructions that go in the loop with the statement: x = x + inc This is not an algebraic formula! The statement tells the computer to add the value of inc (that is, 0.1) to the value of x, making a new value for x. The first time the loop is performed, the calculation will be: x = 0 + 0.1 giving x a new value of 0.1. The next time the loop is performed, x will have a value of 0.2, then 0.3, etc.

52

The line i=i+1 is similar to the previous line, but its adding 1 to i each time. In this case, i is counting the number of loops performed, and is called oddly enough a counter. Counters get used a lot in programming! Incidentally, its very important to know that there is nothing magical about the names i or x that we have been using. You can use just about any name to keep track of the variables, as long as they do not begin with a number. The same goes for the name we gave out procedure. The end of the loop is specified in the line: until (i>=1000) which means that the loop will be repeated until i is greater than or equal to 1000. Thus, the loop is repeated 1000 times, since we are adding 1 to the value of i each time. When the computer reaches the line above, it compares the current value of i with 1000. If its less than 1000, it goes back to the beginning of the loop (the line repeat), and goes through the loop again. Once i is equal to 1000 (or more), the looping ceases and the program continues executing commands at the next line, which is: end This line tells the computer that the end of the procedure has been reached, and to return to the main program. In the main program there are no more lines, so the program stops and gives you the answer, which should be x = 100. The computer has added 0.1 1000 times in the blink of an eye. One last important note: EES requires you to put the procedure first on your code. We did it backwards here to make it easier to follow. Here is the code:

procedure adder(inc:i,x) x=0 i=0 repeat x = x + inc

53

i=i+1 until(i>=1000) end main program inc = 0.1 call adder(inc:i,x)

----------------------------------------------------------------------------------------------------------Problem 4-1 Calculate the amount of interest accrued on a $100,000 loan if the interest is compounded monthly at 6%, over a one year period.

Initial is the amount of the loan, passed from the main program: procedure usurious(initial: total) total = initial repeat total = total * 1.06 icount = icount+ 1 until(icount >=12) end ---------------------------------------------------------------------------------------------------------------------------------

You might ask: What good is this? The answer is that many times you have to break up calculations into many, many small steps. Yo have already seen this when solving a differential equation, which we now do using EES. Recall the differential equation for a falling body through the air that we solved using Excel and Eulers method. We will now repeat the calculation with EES:

500 .07V ^ 2 = mdV / dt You will recall that this equation came from F = ma, and that the dV/dT term is the acceleration a. As mentioned in the Excel chapter, this is a differential equation since it has derivatives in it. Reviewing from the previous chapter, we can approximate the dV/dt term by using finite differences, as follows: dV / dt V / t = (V final Vinitial ) / t In words, dV/dt is approximated by the change in velocity over a time interval (which we will choose. This will give accurate results as long as the time interval is small. If you

54

have not read the section on Excel, please see the section on solving differential equations by Eulers method for some necessary background of what will now follow. We combine the last two equations: 500 0.07V 2 = m(V final Vinitial ) / t The question now is: which V is used on the left side of the equation? Is it the V at the beginning of the time step (Vinitial) or the V at the end of the time step (Vfinal)? The answer is that, as long as we make the time steps small enough, it will not matter. We will use Vinitial, which will allow us to solve explicitly for Vfinal: V final = (500 0.07Vinitial )t / m + Vinitial This equation allows us to march forward in time, using the velocity known from the previous time step, staring with V = 0 at the first step. The beauty of this technique is that it has allowed us to replace a differential equation with no analytical solution with an algebraic equation. What makes the technique possible is the computers speed, allowing us to take thousands or millions of time steps that are sufficiently small. In this problem we are trying to find the terminal velocity of the falling object that is, the point at which there is no further increase in speed. We will know we have reached our solution when Vfinal and Vinitial are equal, or very close to being equal. You get to specify at what point Vinitial and Vfinal can be considered equal. For this problem, we will simply ask the loop to stop when the previous value of V (vold) is equal to the next value. The code below says it all:
"program for finding terminal velocity of falling object" procedure termvel(deltat,mass:time,v) v=0 time = 0 repeat vold = v v = (500 - .07*v^2)*deltat/mass + v "v at end of time step" time = time + deltat "elapsed time" until (v = vold) end "main program" deltat = 0.1 "time steps in seconds" mass = 100 "mass in kg" call termvel(deltat,mass:time,v)
2

The answer comes out to be 84.52 m/s, after 156.4 s. ---------------------------------------------------------------------------------------------------------Problem 4-1

55

Explain the purpose of the line vold = v. ---------------------------------------------------------------------------------------------------------Problem 4-2 Explain the purpose and logic behind the line time = time + deltat ---------------------------------------------------------------------------------------------------------Problem 4-3 Investigate the influence of changing the time step. How small does it have to be so that you no longer get any further significant change in the answer? What happens as you make the time step bigger and bigger? Is there a point where the solution blows up? ---------------------------------------------------------------------------------------------------------Problem 4-4 Write a program that will automatically calculate 5 factorial, using a loop. ---------------------------------------------------------------------------------------------------------Problem 4-5 Write a program that subtracts 100 from 300.15 seventeen times. Use a counter. ---------------------------------------------------------------------------------------------------------Problem 4-6 CERTIFIED TOUGH PROBLEM! A cart is attached to a spring, which is attached to a wall. The cart is pulled so that the spring is stretched 1 m. The spring constant is 3 N/m; in other words, for every m of stretch, the spring exerts a force of 3 N. Find the velocity of the cart after 1 s if the drag force on the cart is 0.1 V^2. This problem is made tougher by the fact that the force on the cart is changing as the springs deflection changes. You have to keep track of the cart location relative to the starting point (at 1 m stretch), which you can do by using the physics formula for displacement s over a time t :

s = Vinitial t + at 2 / 2
Runge-Kutta Integration: EES has a built-in differential equation solver for initial value problems such as the one we just did. Its very easy to use!

"Does 4 order Runge-Kutta Integration of Initial Value Problem" Our DE is dy/dx = (500 - .07*y^2)/100.. at x = 0, y = 0; we want y at x = 156 seconds FUNCTION fRK4(X,Y) fRK4:=(500 - .07*y^2)/100 Notice the function is our D.E. END Y=RK4(LowX,HighX,StepX,Y0) calls the Runge-Kutta solver LowX=0 HighX=156 lower limit of independent variable were starting at t = 0 upper limit of independent variable were going to 156 seconds

th

56

StepX=0.1 Y0=0 $TabStops 1 in

integration step size your time steps initial value of dependent variable y value that goes with LowX

When you run this, you get exactly the same answer we got before!

Conditional Statements and Strings: Consider the paraphrased statement if you see one lamp on, the British are coming by land. If you see two lamps on, the British are coming by sea. This illustrates a conditional statement, which is very useful in programming. Lets do an engineering example. The drag force on a sphere takes a dramatic drop at a speed of about 200 ft/s. Up to 200 ft/s, the drag is given by the equation: Drag = 0.5 V^2 From 200 to 250 ft/s, the drag force is given by the equation Drag = (0.5 * 200^2) (V-200)^2 If V is greater than 250 ft/s, none of our equations work, and we wish to know it. We want a program that inputs the speed in miles per hour, converts it to ft/s, and calculates the drag force. In addition, if the speed is greater than 250 ft/s, we wish the program to tell us. Just a little background information first: recall that we can make EES statements like: x=5 or y=3*x These are mathematical expressions - we are assigning a number or an equation to a variable name (x and y in our examples). However, things do not always have to be so mathematical. Consider the following statement: x$ = hello there

57

In this case, x$ is called a string. A string is a series of letters that you do not perform mathematical operations with. You can give a string any name such as x$, y$, hello$ just about anything as long as it ends with the $ sign, which tells the computer that the variable name applies to a string. In addition, the contents of the string have to be placed in-between apostrophe symbols, as shown above. We will use strings to tell us if the input speed is greater than 250 ft/s. Consider the following program, which will input a speed in miles per hour, convert it to ft/s and calculate the drag force. If the speed in ft/s is greater than 250, the program will warn us. Otherwise it will tell us everything is OK. Lets make a flowchart, which is just a diagram showing the general flow of the program, and the logic. Its sometimes a good idea to make a flowchart, especially when programs get more involved, but it is by no means mandatory many good programmers dont use them. The flowchart will show what is to happen: we will input a speed in miles per hour, convert it to ft/s and calculate the drag force. If the speed in ft/s is greater than 250, the program will warn us. Otherwise it will tell us everything is OK.

Input speed in mph

Covert to ft/s

V < = 250? Calculate Drag END

V > 250? Display error message

The code is shown below; we note that to convert from miles per hour to ft/s, we must multiply by 1.467
"program for finding drag force"

58

procedure dr(vf:note$,drag) if (vf <=200) then drag = .5*vf^2 note$ = 'OK' endif if (vf > 200) and (vf <=250) then drag = (.5*200^2) - (vf-200)^2 note$ = 'Drag dropping' endif if (vf>250) then drag = 0 note$ = 'Too big a speed' endif end "main program" v = 230 "convert to ft/s" vf = v*1.467 call dr(vf:note$,drag)

Note in the second if statement we are using two conditional statements: if vf is greater than 200, and less than 250, then You can put any number of these together. You can also use an or statement, as shown below: if (v > 30) or (p< 350) then -----------------------------------------------------------------------------------------------------------Write a program that loops the equation: x = (x*1.01)^1.01 ten times. If the result is bigger than 5 or smaller than or equal to 5, then some appropriate message is to come up. x is initially equal to 1. -----------------------------------------------------------------------------------------------------------Write a program that loops the same equation, but also loops (in the same loop) y = y + 1 10 times. If the resulting x>5 and y > 11 print case 1, if x>5 and y<=11 print case 2, if x<=5 then print wow. x is initially 1 and y is initially zero. ----------------------------------------------------------------------------------------------------------Write a program that looks at a number w, and, if w is greater than or equal to 10, executes a loop in which 5 is squared 3 times. The squaring three times is to be done using a repeat loop. If w is less than 10, 5 is multiplied by 2. If another number q is greater than w, or if q is greater than 5, then a message is to read Hello. Otherwise, the message is to read Goodbye. ------------------------------------------------------------------------------------------------------------

59

Arrays, Nested Loops Recall the problem in which we were finding the terminal velocity of the falling object. We developed a program that did the required job, which was to march forward in time steps and calculating the velocity at each time step. When the velocity at any time step is equal to the velocity of the previous time step, then we know that the object is no longer accelerating and that terminal velocity has been reached. The terminal velocity was then displayed. But what if we had wanted to store some or all of the intermediate velocities? In other words, what if we want to know V after 1 second, or after 13 seconds? Using arrays it becomes easy to store the intermediate values of any variable. We will call the velocity at time step 1: V(1). The velocity at time steps 2 and will be called V(2) and V(3). You may see a pattern emerging! A variable name followed by a number in parentheses is called a one-dimensional array (a two-dimensional array would be a name followed by two numbers, such as x(1,3), but well stick to one-dimensional arrays here). You can see that its just another way of giving names to variables, but it turns out a much more convenient way when you have to store many values. Below we present the previous code. Note that intermediate values of velocity v are lost whenever a new velocity is calculated:
"program for finding terminal velocity of falling object" procedure termvel(deltat,mass:time,v) v=0 time = 0 repeat vold = v v = (500 - .07*v^2)*deltat/mass + v "v at end of time step" time = time + deltat "elapsed time" until (v = vold) end "main program" deltat = 0.1 "time steps in seconds" mass = 100 "mass in kg" call termvel(deltat,mass:time,v)

Now consider the following code, which will calculate the velocity at the first ten time steps only, but will store and display those ten velocities:
"program for finding velocity of falling object at intermediate time steps" procedure termvel(deltat,mass:time,v[1..10]) v[1]=0 time = 0 i=1 repeat v [i+1]= (500 - .07*v[i]^2)*deltat/mass + v [i]"v at end of time step"

60

time = time + deltat "elapsed time" i=i+1 until (i = 11) end "main program" deltat = 0.1 "time steps in seconds" mass = 100 "mass in kg" call termvel(deltat,mass:time,v[1..10])

Lets look at this program step-by-step, starting with the main program at the bottom. The main program defines the time step deltat and the mass, then calls procedure termvel. Notice that it passes inputs deltat, and mass to the procedure, and specifies that time and v[1..10] will be the outputs. v[1..10] means that we are instructing EES to display in our solution velocities 1 through 10. We could have written just, say v[4], and then only v[4] would have been displayed. Procedure termvel at the top of the program is first given the initial value of v=0 at time step one (v[1] = 0). We initialize the time as zero, just as the previous program, and begin a counter i. Now comes the part that might throw you for a loop. Inside the loop, notice the line:
v [i+1]= (500 - .07*v[i]^2)*deltat/mass + v [i] [1]

Recall that we are using the previous time steps velocity to calculate the current time steps velocity. If i = 1 (the first time the loop is executed), then the equation above will be understood by the computer as:
v [2]= (500 - .07*v[1]^2)*deltat/mass + v [1]

The second time the loop is repeated, counter i will equal 2, and the computer will understand equation [1] as:
v [3]= (500 - .07*v[2]^2)*deltat/mass + v [2]

Do you see what is happening? Thanks to the array, we have written one equation that is good for all of the time steps, without having to write the equation out many, many times! In addition, we are storing v[1] through v[10]. At the end of each loop we update the counter by:
i=i+1

And finally, the loop is instructed when to finish by the line


Until (i = 11)

61

This may seem confusing since we want the loop to be executed ten times, but notice that in the statement before this one we are adding one to i, so the loop will have executed ten times when i = 11. When you run this program, the ten velocities will be displayed in the Arrays Window after running the program, go to Windows/Arrays to see your solution. ----------------------------------------------------------------------------------------------------------Homework: For flow between parallel plates, with one plate moving at u = 100 m/s and the other stationary, the velocity at any point is equal to the average of the velocities above and below it: u=100 m/s 1 2 y 3 4 5 6 Stationary Plate u = 0

We then have the following 6 equations: u6 = 0 u5 = (u6 + u4 ) / 2 u4 = (u5 + u3 ) / 2 u3 = (u4 + u2 ) / 2 u2 = (u3 + u1 ) / 2 u1 = 100 We need to solve these equations simultaneously. One way to do this is by Gauss-Seidel iteration. To do this, you assign an initial value to all the us, say 1, and then just keep looping through the equations. The equations will keep changing with each loop, until they stop changing known as convergence). When this happens, the simultaneous equations can be considered to have been solved. We will use arrays to keep track of each u, and to only have to write the equation for u once.

62

Write a program to do the following (remember that all programming such as looping and conditional statement must be done in a procedure, and that the procedure must be called from the main program at the bottom of the program) a) Using arrays, set u(1) and u(6) to 1000 and 0, respectively. b) Initialize all the u values (u(2) u(5) to a value of 1. hint: i=2 repeat u(i) = 1 i = i+1 until(i>5) b) loop through the equations 100 times: u(i) = (u(i+1) + u(i-1) )/2 c) Print to the screen all the u values. Have the computer give you a warning if u(2) is greater than 50.

63

LOOK-UP TABLES/INTERPOLATING AND DIFFERENTIATING FUNCTIONS


"This example demonstrates the use of the Lookup table and the Interpolate and Differentiate functions. " What is y at x = 3.1?" y1=interpolate('x','y',x=3.1) "note that the single quotes are optional" "find x at y = 12.8" x1=interpolate('x','y',y=12.8) " Estimate dydx at x = 3" dydx=differentiate(x,y,x=3) "Note that values were put into a look-up table using the Tables/New Lookup Table. Click on each column to give it a " "name" "Lookup values" "X Y" "1 2" "2 4" "3 9" "4 16"

64

CHAPTER 4: MATLAB
Matlab is a powerful engineering tool that allows you to program, and also has many built-in functions to help engineers do their jobs more effectively. Matlab is becoming very popular in academia and industry. Symbolic Mathematics Matlab has the capability of to do symbolic mathematics, that is, solve equations with variables in them, such as x 2 dx = x 3 / 3 . This is a feature that sets Matlab apart from

many other software packages in use by engineers.

If you have not already done so, install the Matlab software on your computer by following the instructions which appear when you load the disk. Choose the standard installation option. Before you begin: use the same notation you as in other languages: +,-,*,/ and ^ for raising to a power. In addition, the standard hierarchy of operations applies. We now explore some of the capabilities of the Matlab product: a) Type in the following command, which tells Matlab that the expression within the apostrophe marks is a symbolic expression: y = sym(x^3 2*y^2 + 3*a) and hit the return key. The output on your screen is: y = x^3 2*y^2 + 3*a OK, that was not too hard. Now do the same for the following expressions:

A = x 2 25 B = ( x 5) 2 C= ( x 2 5 x 10) x+2 3 D = x + 3 x 2 13 x 10 E = 2 x 3 y + 4 x + 13m 8 y Please note that Matlab will distinguish between A and a in the names of the expressions above.

65

b) The command ezplot makes a plot of symbolic expressions. Here is the format: ezplot(A,[xmin,ymin]) This expression plots equation A from xmin to ymin. Try it for expression A, from -1 to 1. You should get the following plot

We will look at plotting more closely soon, but for now, typing in the following commands will give you a title and x,y labels: title(plot) xlabel(x) ylabel(y) Make a plot for expression B. Equations may be manipulated easily in Matlab. Here are some examples: c) factor(A) the answer should be (x+5)(x-5) d) expand(B) e) simplify(C) in this case, the equation cannot be simplified further! f) factor(D)

66

The simplify function above gives only one result only. There may be others: simple(C) gives several other attempts at simplification, and ans will be the shortest one. g) Come up with a symbolic expression that is greatly simplified by the simplify command.

67

SOLVING SIMULTANEOUS EQUATIONS IN MATLAB: You will probably encounter simultaneous equations in electrical engineering and heat transfer. It is very simple to use Matlab for solving simultaneous equations one advantage over the techniques used so far is that there is no need to tell Matlab the range of the solutions, nor where to start iterating . This is because Matlab uses matrix algebra to solve simultaneous equations, as opposed to iterative schemes. Matlab should give you every solution that exists not just the ones within a specified range. Its then up to you to decide which solutions are good or not. Lets say you have the following equations: 3x 2 y 2 = 0 12 x 2 y = 3 We wish to find the solution, or solutions to these equations. Type in: s = solve(3*x-2*y^2, 12*x-2*y=3) Press enter. Note that if an equation is equal to zero, there is no need to specify that its equal to zero, as in the first equation. Note that the second equation is not equal to zero, and the entire equation is written out. The result tells you the size of the matrix of each answer.. pretty confusing and useless to us. Now type in: M = [s.x, s.y] This instructs Matlab to give the solution for x and y from s, and to put the solution in a matrix called M. The result is:
M = 1/ 6 1/ 2 3/8 3/ 4

This means that x = 1/6 , y = -1/2 is one solution, and x=3/8, y = is another solution. Note that when you defined M, you told Matlab how to present the data to you. If you had typed in M = [s.y, s.x] the solution would have been:

68

M =

1/ 2 1/ 6 3/ 4 3/8

These fractions are a little annoying, so we get rid of them by typing in: vpa(M, 5), which gives you 5 digits in the answer: M = .16667 .50000 .37500 .75000

Try solving the following equations: 10 x 3 + 2 y = 5 z 6x 2z = y z = 5 x + 6 y The solution matrix for x, y, z is (using 4 digits):

0 0 0 M = .973 1.198 2.320 .973 1.198 2.320


In other words, x = 0, y = 0, z = 0 is one solution. x = .973, y = 1.198, z=2.320 is another, etc. Solve the simultaneous equation solved earlier: Qtotal = 1.712E-9 * (1000^4 T1^4) + 5* ( 90 T1) Qtotal = 100*(T1 T2) Qtotal = 25 *(T2 30) There will be four solutions: one will have negative temperatures, and two others will have unreal solutions with the number i. The solutions should be q = 1712, t1 = 115.6 and T2=98.47, using 4 digits in the vpa command.

We note that it appears that this procedure is the easiest so far s compared with Excel and EES, once the syntax has been learned.

69

DIFFERENTIATION AND INTEGRATION. M FILES. Taking derivatives and performing integration are very simple with Matlab, but before we do that, its a good time to talk about M-files. Have you noticed that we seem to be able to put in only one Matlab command at a time at the EDU prompt? We would like to write longer sets of instructions that is, we will be writing programs. Programs in Matlab are known as M-files. M-files allow you to write a series of instructions, not just one instruction at the prompt, as we have been doing. Making an M-file is simplicity itself. Go up to File/New/M-file on the upper left corner of your screen, and click on the M-file. A blank screen will appear in which you can type in your commands. Type in the following:
% Note the % character is for making comments sa= sym('6*x^3 - 4*x^2+b*x') sb=sym('sin(a)'); %semi-colon is there to suppress printing "sin(a)" %on the screen when the program runs. sc=sym('(1-x^3)/(1+x^4)') %syntax for differentiating sa twice is: diff(sa,'x',2) % sa is the symbolic expression to differentiate, 'x' is the variable with % respect to which differentiation is done, and 2 is the number of times to % take derivative. sadif=diff(sa,'x',1) sadif2=diff(sa,'x',2) sbdif=diff(sb) %leave out the extra parameters and it does 1st derivative % wrt variable closest to letter "x". In this case there % is only one variable, a scdiff=diff(sc)

Run it by hitting the F5 key. To see the output, return to the main window, which should be accessible on the upper or lower edges of your screen. You will see the answers:

sa = 6*x^3 - 4*x^2+b*x sc =(1-x^3)/(1+x^4) sadif = 18*x^2-8*x+b sadif2 = 36*x-8 sbdif = cos(a)

scdiff =-3*x^2/(1+x^4)-4*(1-x^3)/(1+x^4)^2*x^3

70

Notice that the expression for sb was not printed in the output. This is because we suppressed it by using the semi-colon. There are times, especially when you may have very long expressions, that you will want to do this. The last expression looks complicated. Maybe we can simplify it. Add the line simplify(scdiff) to your program: ans = x^2*(-3+x^4-4*x)/(1+x^4)^2 You can also make it easier to look at by using the pretty command: pretty(ans) Heres the output:

2 4 x (-3 + x - 4 x) -----------------42 (1 + x ) Next lets try integration. Lets modify the old program to avoid typing in more characters.
% Note the names sa, sb and sc are not magical! % just about any name will do - cannot start with a number sa= sym('6*x^3 - 4*x^2+b*x') sb=sym('sin(a)') sc=sym('(1-x^3)/(1+x^4)') %syntax for integration is int(sa,'x') % sa is the symbolic expression to differentiate, 'x' is the variable % with respect to which integration is done saint=int(sa,'x') sbint=int(sb,'a') scint=int(sc,'x',1,3) %definite integral from 1 to 3 wrt x scintsimpler=simplify(scint)

Heres the output (Note that sb is no longer suppressed, and that the final equation appears to be in its simplest form before the simplify command!) sa = 6*x^3 - 4*x^2+b*x sb = sin(a) sc = (1-x^3)/(1+x^4) 71

saint = 3/2*x^4-4/3*x^3+1/2*b*x^2 sbint = -cos(a) scint = 1/8*2^(1/2)*log(3*2^(1/2)+10)-1/8*2^(1/2)*log(3*2^(1/2)+10)+1/4*2^(1/2)*atan(3*2^(1/2)+1)+1/4*2^(1/2)*atan(3*2^(1/2)-1)1/4*log(41)-1/8*2^(1/2)*log(2+2^(1/2))+1/8*2^(1/2)*log(2-2^(1/2))-1/8*2^(1/2)*pi scintsimpler = 1/8*2^(1/2)*log(3*2^(1/2)+10)-1/8*2^(1/2)*log(3*2^(1/2)+10)+1/2*2^(1/2)*atan(3*2^(1/2)-1)+1/4*2^(1/2)*atan(1/9)-1/4*log(41)1/8*2^(1/2)*log(2+2^(1/2))+1/8*2^(1/2)*log(2-2^(1/2))-1/8*2^(1/2)*pi

72

SOLVING DIFFERENTIAL EQUATIONS WITH MATLAB. FUNCTIONS. MORE PLOTTING. Matlab has the capability to solve complex differential equations, far in excess of EES. Lets start with the differential equation we have come to know so well, for a falling object subject to a drag force. You will recall that its an ordinary differential equation, and that we solved this using Eulers method before, by marching forward in time: 500 .07V ^ 2 = mdV / dt We wish to solve this using an intial value of V = 0, and we wish to know the speed V as a function of time. In order to do this, we must fist learn how to use functions. A function is a program you write that you will call from another program. Its similar to a procedure in EES. Lets make a function that converts degrees to radians. We first make an M-file that will call a function called DegtoRad. Note we will be passing the value of degrees to the function, and that we do not need to specify what the output will be. Name it anything you like:
%program to call a function called DegtoRad %which converts degrees to radians degrees = 15 radians = DegtoRad(degrees)

Now we actually define the function. Make another M-file and make sure you save it using the name of the function, which in this case is DegtoRad
%illustrates use of a function to make a %calculation. It's very important that the %function name DegtoRad is the name under %which M-file is saved. function output=DegtoRad(x) output=x*pi/180;

Just run the main program by hitting F5, while in the main program. Your output should be:

degrees = 15 radians = 0.2618


Functions are not just for solving differential equations. They can be very useful in that you could write a function that you could call from any other program, without having to re-write whats in the function. -----------------------------------------------------------------------------------------------------------Problem Write a function that converts from Centigrade to Fahrenheit

73

-----------------------------------------------------------------------------------------------------------Now that you know how to use a function, we can continue with our differential equation equation: 500 .07V ^ 2 = mdV / dt Recall that the mass is 100, and that the initial velocity at time zero is zero. We will be using a pre-made (it comes with Matlab) differential equation solver, ode45, which solves initial value problems like ours, in a similar way to the programs you have been writing to use Eulers method. You will need two M-files: one to define the problem, and a function that ode45 will access. Following is the first M-file. The differential equation is for dV/dt, so the variables are t and v:
%for solving a d.e. [t,v] = ode45('termvel',[0,156],0) %termvel is the name of the function %that the function ode45 will be %calling. The equation will be %evaluated from t= 0 to t = 156 (in %the brackets), and the initial %value of the velocity is zero. plot(t,v) xlabel('time(s)') ylabel('velocity (m/s)') %lets plot it

The function which is used by the differential equation solver is then made. You must save it under the name of termvel (in this case)
function dydt=termvel(t,v) dydt=(500-.07*v^2)/100;

Thats all there is to it! Now go to the first program above and run it. Heres the output plot:

74

The terminal velocity is about 85 m/s, based on the plot. The numerical output gives it at about 84.5 m/s, which is what we had earlier. You may notice that Matlab presents the numerical output in a rather annoying way: it lists all of the times, then the velocities. You can add the following line to your main program:
table=[t,v]

to get the output in a table format, with t and v presented in columns. Please explore the Help section for more detail, as there are other options you can use here. The next page has the output.

75

table = 0 0.0000 0.0000 0.0000 0.0000 0.0001 0.0001 0.0002 0.0002 0.0005 0.0007 0.0010 0.0012 0.0025 0.0038 0.0050 0.0063 0.0125 0.0188 0.0251 0.0314 0.0628 0.0942 0.1256 0.1570 0.3140 0.4710 0.6280 0.7850 1.5699 2.3549 3.1398 3.9248 7.1834 10.4419 13.7005 16.9590 19.1167 21.2744 23.4320 25.5897 27.7474 29.9050 32.0627 0 0.0001 0.0001 0.0002 0.0002 0.0005 0.0007 0.0010 0.0012 0.0025 0.0037 0.0050 0.0062 0.0125 0.0188 0.0251 0.0313 0.0627 0.0941 0.1255 0.1569 0.3139 0.4709 0.6279 0.7849 1.5697 2.3542 3.1384 3.9220 7.8271 11.6988 15.5211 19.2788 33.8907 46.4442 56.6252 64.4850 68.5772 71.9064 74.5798 76.7114 78.4103 79.7507 80.7986

76

34.2204 36.9847 39.7491 42.5135 45.2778 48.4662 51.6546 54.8431 58.0315 61.9315 65.8315 69.7315 73.6315 77.5315 81.4315 85.3315 89.2315 93.1315 97.0315 100.9315 104.8315 108.7315 112.6315 116.5315 120.4315 124.3315 128.2315 132.1315 136.0315 139.9315 143.8315 147.7315 151.6315 152.7236 153.8157 154.9079 156.0000

81.6185 82.4248 83.0097 83.4218 83.7182 83.9736 84.1481 84.2592 84.3341 84.4054 84.4496 84.4706 84.4828 84.4956 84.5036 84.5073 84.5095 84.5118 84.5133 84.5140 84.5144 84.5148 84.5150 84.5152 84.5152 84.5153 84.5154 84.5154 84.5154 84.5154 84.5154 84.5154 84.5154 84.5154 84.5154 84.5154 84.5154

77

If a solution cannot be obtained using ode45, there are other built-in differential equation solvers in Matlab. You might try ode15s if ode45 does not work, or consult the Help section. -------------------------------------------------------------------------------------------------------Problem dy t 3 2 y = for t from 1 to 3.5, with y = 4.2 at t=1. Plot it, and Solve the equation dt t create a table to view the results. Solution: y = 5.844 at t =3 -------------------------------------------------------------------------------------------------------Problem The cooling of a ball initially at 400 F, placed in 70 degree F air is governed by the differential equation:
dT = 12(T 70) dt where the upper case T is temperature in degrees F, and the lower case t is time, in hours. Make a plot of the temperature of the ball for the first hour. --------------------------------------------------------------------------------------------------------Problem A ball is shot upward from an underwater cannon, at 5 m/s. The drag force on the ball is given by the equation: drag = 100 V^2 The ball has a mass of 1 kg, and a buoyant force (upwards) of 30 Newtons. Make a plot of the velocity of the ball as a function of time, and find the terminal velocity of the ball. ---------------------------------------------------------------------------------------------------------

78

Plotting with Matlab. Matlab has the capability to do very sophisticated 2-D and 3-D plotting. We now look at some of the plotting features. Please note that we are only looking at a few of the plotting features. Readers needing more detail are encouraged to use the Help section of the software, which is very extensive. One of the strengths of Matlab is its ability to work with matrices in fact, the name Matlab stands for Matrix Laboratory. Matlab is great for manipulating matrices, and was designed to do so. Hence, many features of Matlab use a matrix format or language from linear algebra. You will see this as we go along. An array is a list if numbers or symbols arranged in rows and columns. For example: 2 3 8 6 is a 2 x 2 matrix, with two rows and two columns. The simplest array is one row, or one column. Rows move horizontally, while columns move vertically. A row is sometimes referred to as a vector. OK, thats enough about matrices for now. Type in the following M-file:
x=[1:1:10]; %creates values from 1 to 10 in steps of 1 %also, created a vector called x y=[1,3,4,5,7,9,9,10,7,5]; %vector y with assigned values z=[2:2:20]; %vector z from 2 to 20 step 2 plot(x,y,x,z) %we plot y vs x, and z vs x on same plot title('1st plot') xlabel('Distance(m)') ylabel('Velocity(m/s)') grid on %put on a nice looking grid hold on %put one more plot on same graph %note that we could have used the %1st plot statement, and just add %z,y to it. hold on tells %Matlab to use the same plot as before plot(z,y)

Lets see how we can make the plot look better. Modify the plot commands as follows:
plot(x,y,'r--',x,z,'y-') %we plot y vs x, and z vs x on same plot plot(z,y,'b:+')

You will see the plot now has different color lines, different line styles (dashed), and the last plot has data markers.

79

Heres how it works: after the list of data pair to plot (x,y in our case), you can have up to 4 characters inside the apostrophe marks (there does not have to be four, but 4 is the max) designating the way in which the data are plot. Color markers: c (cyan) m (magenta) y, r, g, b ( you can figure these out! b for Blue) k (black)

Line type characters: - (solid line) -- (dashed line) : (dotted line) -. (dash-dot) Data markers: + o * x s (square) d (diamond)

Example: plot(x,y,ks) would plot a black line with square data points marked. There is no need to insert spaces between the markers, but they must all be within the apostrophes. There are many more plotting features that you should explore on your own using Help, should you desire them. In particular, on the figure itself you will see a toolbar on which you can access features such as legends, fonts, etc. Curve-Fitting Matlab has some very powerful curve-fitting features. You have already seen curvefitting in the Excel portion of this course. Again, we are interested in getting an equation to a line based on the values of data pair. The easiest way to get a fit to a line in Matlab is to use a plot. Go to the plot you just created, and click on Tools/Basic Fitting. A window will appear on the upper left of your screen. You will see an arrow at the bottom. Click on the arrow to open up the second half of the window. You should see the image below:

80

You will also notice that, on the graph, each plot is given a name on the plot. Select the data1 set of data, and select the quadratic fit (A 2nd degree polynomial; cubic is third). You will now see that the coefficients to your fit are expressed in the window:

81

The residuals indicate the goodness of the fit. Now look at the plot:

82

Notice that the fit through the data is presented as a light blue line, and that the fit extends BEYOND the range of the data (the data for the data 1 set stop at x = 10). This is because data set 3 goes to x = 20. Matlab draws the fit to the end of the graph. You should now experiment changing the fit to 3rd, 4th and 5th degree polynomials. The really nice thing about Matlab is that you can instantly see the effects and compare each fit. Matlab also gives you the option to create a fit from the M-file. Please see the Help section for more details. ---------------------------------------------------------------------------------------------------------Problem Use your thermodynamic tables to make a plot of Pressure (y-axis) as a function of Temperature for the saturated steam tables. Make a fit to T as a function of P. Use a dashed line for your plot, with data symbols. Label the axes and the plot. ----------------------------------------------------------------------------------------------------------Problem Make a plot of Pressure P (y-axis) as a function of enthalpy h. Try to make a polynomial fit to P as a function of h.

83

----------------------------------------------------------------------------------------------------------Problem Use the Help Section to investigate how to make several plots on one page using the subplot command. Make 4 plots on one page they can all be the same. -----------------------------------------------------------------------------------------------------------

3D Plotting
Lets say that we wanted to make a plot of P, v, T values from the superheated steam tables. We will enter the following values from the tables: P 5 5 5 10 10 10 20 20 20 T 200 280 320 200 280 320 230 280 320 v 78 88 93 38 44 46 20 22 23

Type in the following M-file code:


%for 3d plot of superheat tables p=[5,10,20] t=[200,280,320] [p,t]=meshgrid(p,t) v=[78,88,93;38,44,46;20,22,23] %mesh(p,t,v) surf(v,t,p) shading interp zlabel('Pressure(psia)') ylabel('Temperature(F)') xlabel('sp. vol (ft3/lbm)')

Notice that we initially made vectors to specify all of the p and t values, then used the meshgrid command to make an array out of the p,t pairs. Then, the v values that go with each p,t pair are specified in array v. We note that the same T values must be used at each pressure. The plot below is the result:

84

85

PROGRAMMING IN MATLAB You can write extensive programs in Matlab M-files. Matlab has all of the programming features you have already seen, such as loops, conditional statements and arrays. Looping is done using the for statement, as shown in the code below:
%looping x=0; for i=1:2:10 % from one to ten in steps 2 x = x + 1 end % end closes a loop

Notice that when you run this code, x is printed on your screen each loop. We will suppress the printing by using the semi-colon, and instruct Matlab to print the final answer:
%looping x=0; for i=1:2:10 % from one to ten in steps 2 x = x + 1; end % end closes a loop disp('x') %display the letter x disp(x) %display the value of x

There is also a formatted print statement, which allows you to print more than one result per line, and allows you to specify the number of characters to display.
x=0; for i=1:2:10 % from one to ten in steps 2 x = x + 1; end % end closes a loop fprintf('\n x is %f',x) %fprintf('\n x is %f i is %f',x,i) %prints only a string (characters)

The \n tells Matlab to skip a line, while the x is are characters you want printed. The %f tells Matlab to use notation with decimals for the x result. Try uncommenting the last command and running it. It should print two results to the screen. There are many more options for using the fprintf command. Please consult the Help section of your software if you are interested. Its possible to put a loop within a loop, known as nested loops. Consider the code below:
%looping x=0; for i=1:2:10 %outer loop for j=1:1:3 %inner loop

86

x = x + 1; %closes the inner loop end %closes the outer loop fprintf('\n x is %f',x) fprintf('\n') %to skip a line and get rid of EDU prompt end

Run the code. Notice that there are two end statements, one for each loop. Incidentally, the indenting was done only to make it easier to see whats going on. Also notice that we put in an additional fprintf statement to skip a line, so the output looks better. ----------------------------------------------------------------------------------------------------------Problem For the commands:
for i=1:1:3 %outer loop for j=1:1:4 %inner loop x = x + 1; end %closes the inner loop end %closes the outer loop

What will be the final value of x, assuming it was 0 at the beginning of the program? Do not write a program to do this. ---------------------------------------------------------------------------------------------------------Problem Write a program that will loop 100 times using the for command, using a counter to verify that the loop has indeed been done 100 times. Note that x is a counter in the code above. ---------------------------------------------------------------------------------------------------------Problem Write a program that loops 10 times in the outer loop and 5 times in the inner loop. How many iterations are done. Use a counter. -----------------------------------------------------------------------------------------------------------

SOLVING SIMULTANEOUS EQUATIONS WITH GAUSS-SEIDEL ITERATION Its possible to solve simultaneous equations by looping through them many times a technique known as Gauss-Seidel iteration. For example, consider the simultaneous equations below:
u1 = (100 + u 2) / 2 u 2 = (u1 + u 3) / 2 u3 = u 2 / 2 Lets loop through them a few times and see what happens. We will set all the u values to 1 at the beginning of our looping.

87

First loop: u1=(100+1)/2 = 50 u2 = (50+1)/2 = 25.2 u3 = (25.2/2) = 12.75 2nd Loop: u1 = (100+25.2)/2 = 62.6 u2 = (62.6+12.75)/2 = 37.675 u3 = (37.65 /2) = 18.83 3rd loop u1 = (100+37.65)/2 = 68.85 u2 = (68.85+18.83)/2 = 43.83 u3 = (43.83/2) = 21.91 4th loop u1 = (100+43.83)/2 = 71.9 u2 = (71.9+21.91)/2= 46.9 u3 = (46.9/2) = 23.46

%Note that we have a new value for u1 now % we now have a new value for u2

If we were continue this process for a while longer, we would eventually reach u1 = 75, u2= 50, u3 = 25. If you were to continue looping after this point, there would be no further change in the u values. The technique we have just outlined is known as Gauss-Seidel iteration. It works as long as the equations are in the proper format, so that they satisfy the Scarborough criterion. The Scarborough criterion says that Gauss-Seidel iteration is guaranteed to converge if the following is true:

For all equations, the sum of the LHS coefficients divided by the sum of the RHS coefficients must be < = 1. For example, in the first equation, the sum of the left coefficients is 1, while the sum of the right coefficients is :
1st equation: 1/(1/2) = 2 Scarborough criterion not met! 2nd equation: 1/(2/2) = 1 OK Scarborough criterion not met! 3rd equation: 1/0.5 = 2

For at least one equation, the sum of the LHS coefficients divided by the sum of the RHS coefficients must be less than one. This is not met, either.
Gauss-Seidel iteration may still work if the Gauss-Seidel criterion is not met, but its guaranteed to work if the criterion is met. ------------------------------------------------------------------------------------------------------Problem Consider the 4 equations:

88

x= 5 - y ; z = x + 6 y ; q = 2 y 2x ; y = -2 q x Check to see if they meet the Scarborough Criterion.(Sum of the coefficients for the last equation: 1/(-1 + -1) = -0.5). Loop through the equations using a calculator, and setting all the unknowns to 1 at the beginning. Continue looping until there is no longer any change from loop to loop. The final answers: x = 4, y = 1, z = 9, q = -7 -----------------------------------------------------------------------------------------------------------Write a Matlab program to loop through the equations 100 times (the number 100 is a guess that it will take fewer than 100 loops to solve this problem. The larger the number of equations, the larger the number of iterations required. Print the solution. -----------------------------------------------------------------------------------------------------------Modify your Matlab program so that the value of the u2 is plotted as a function of the number of iterations. You may have to use the hold on command. ----------------------------------------------------------------------------------------------------------Conditional (If) Statements: If statements are easy to implement in Matlab. Consider the following code, which also shows you how to input data from the program user:
hat = input ('Your hat size'); if hat >= 3 fprintf('You have a big head') %else % fprintf('You have a small head ') end

You can see that this is very similar to the EES format. Note that every if statement must be closed with an end statement everything between the if and the end is part of the conditional statement. --------------------------------------------------------------------------------------------------------Problem Activate the commented (%) lines in the code above. You will see that the else statement is executed if the if statement does not apply. --------------------------------------------------------------------------------------------------------Problem The drag coefficient (cd) of a disc moving through the air is given by the values below. The cd vector is the drag coefficient, and the v vector is the velocity, from v = 10 to v = 40:
cd = [1.9,1.5,1.75,1.5] V = [10,20,30,40]

From v = 40 to 90, the drag coefficient has different values:


cd2=[1.5,1.1,1.25,1.1,1,1] v2=[40,50,60,70,80,90]

89

Make a polynomial fit to Cd as a function of the velocity for the first set of data and another for the second set of data. Write a program that inputs the speed from the program user. If the speed is greater than 90, then a message should say the velocity is too great. For velocities between 0 and 90, the program should calculate the drag coefficient, based on the right formula (As determined by the input speed). ---------------------------------------------------------------------------------------------------------While Loops In EEs you encountered the repeat/until commands. You will recall that this involved running a loop until a certain condition was met. In Matlab you can perform loops until a condition is met using the While statement. Consider the code below:
% while-end loop x = 0; while x <=10 x = x+1; fprintf(' %4.0f', x) end

You can pretty easily figure out what is going on the loop is performed until x is greater than or equal to zero, and x is incremented by a value of one each loop. Please note that every while loop must have an accompanying end statement. -----------------------------------------------------------------------------------------------------------Problem Write a Matlab program using a while loop that divides the number 100 by a value of two, until the result is less than or equal to 17. What is the final result, and how many loops are performed. Your program must give the final answer and count the number of loops. -----------------------------------------------------------------------------------------------------------Problem Write a Matlab program using a while-loop. The program is to start with the number 100, and is to divide it by 2. Next loop it is to divide the result by 2 again, and to repeat the process until the change in the result from loop to loop is less than 0.25. For example: 1st loop: x = 50, change in x = 50 Loop 2: x = 25, change in x = 25 Loop 3: x = 12.5, change in x = 12.5 Heres a program to do it:
% while-end loop

90

x = 100; dif = 10000; % a safe value to make sure loop executes the first time xold = 1000; % a safe value to make sure loop continues on 1st loop while dif > 0.25 % loop executed while the difference between x values % w is less than 0.001 x = x/2 dif = abs(xold-x); xold = x; i = i+1; %a counter end disp('x') %disp is quick way to show answers or strings without %formatting disp(x) %actual answer for x disp('') %print a space disp('i') disp(i)

-----------------------------------------------------------------------------------------------------------Problem Write a program that first adds 10 to 100, then 5 to the result (that is, 110+5) , then adds 2.5 (115+2.5), and continues this pattern, until the change is less than 0.001. Display the final result, and count the number of loops executed. The code below does it. You will need to understand it to do the next problem, or one of your own (there are many ways to solve most programming problems!):
% while-end loop dif = 10; % need this statement so loop will be satisfied first loop xold = 1000; % on first loop there is no xold yet, so pick a safe value x=100; % starting value to add to po = 20; % need this in first line in loop i = 0 while dif > 0.001 % loop executed while the difference between x values % w is less than 0.001 x = x+po/2; %calculate x dif = abs(xold-x); %calculate abs value of difference between old % and new x xold = x; %value of x juts calculated becomes xold po = po/2; %cut increment by one half i = i+1; %counter end disp('x') %disp is quick way to show answers or strings without %formatting disp(x) %actual answer for x disp('') %print a space disp('i') disp(i)

----------------------------------------------------------Problem

91

When we wrote the Gauss-Seidel program above, we assumed that 100 iterations were sufficient for the variables to stop changing from loop to loop. Write a program that performs Gauss-Seidel iteration on the same simultaneous equations used earlier in the Guass-Seidel section, but instead of using a for-loop that loops 100 times, use a whileloop that stops when the 3rd equation changes by less than 0.0001. ----------------------------------------------------------------------------------------------------------Problem Solve the differential equation we have been using: 500 .07V ^ 2 = mdV / dt where m = 100, and V = 0 at t = 0. Loop through the equation until terminal velocity is reached, and display the value of the terminal velocity. Define terminal velocity as occurring when the velocity changes less than 0.01 m/s per loop. ----------------------------------------------------------------------------------------------------------Class Project Make a Matlab program to input Pressure in psia, and output the following: saturation temperature (F and C), hf and hg (in BTU/lbm and kJ/kg), sf and sg (BTU/lbm-R and kJ/kg-K), vf and vg (ft^3/lbm a,d m^3/kg). Use a different function for each. Input the U.S. units, and use conversion factors to calculate the SI values. Have the program tell you the units of each answer. The class will be broken up into groups, and each group will fit a different property, after which all the data will be shared. You may input every other value from the steam tables, as long as you include the lowest and highest value on the table. Do this two ways: 1) using curve-fitting (if it is not possible to fit some of the data well, you may have to break it up into sets for example, from 10-500 psia, and from 500-700 psia, etc.) 2) By having Matlab look at the values in a table, and interpolating between values. Matlab can automatically do this for you using the interp1 function (last letter in the number 1). For example: say you had the following values for temperature and internal energy:

T= [100, 150, 200, 250, 300, 400, 500]; u = [2507, 2583, 2658, 2734, 2810, 2968, 3132]; and you wanted to know the value of u that went with a temperature of T = 215. Here is the code:
%for interpolating

92

T= [100, 150, 200, 250, 300, 400, 500]; u = [2507, 2583, 2658, 2734, 2810, 2968, 3132]; u2 = interp1(T, u, 215) u2cube = interp1(T,u,215,'cubic')

By default, Matlab uses a linear interpolation between points. In other words, it drew a straight line between the u value at T = 200 and T = 250, and used y = mx + b to find the u value at T = 215. Its more accurate to use a cubic interpolation, which fits the data near the point you want to a third degree polynomial, so get a more realistic result if the data are curved. In the example above, we found the u value that went with a T value of 215. We can easily find a T value that goes with a u value. For example, to find the T that goes with u = 3000,
%for interpolating T= [100, 150, 200, 250, 300, 400, 500]; u = [2507, 2583, 2658, 2734, 2810, 2968, 3132]; u2 = interp1(u, T, 3000) u2cube = interp1(u,T,3000,'cubic')

3) Calculate the % difference between the cubic and linear interpolations. -----------------------------------------------------------------------------------------------------------Problem Write a program that asks the user for input. If the user inputs the number 1, the user inputs a pressure, and the program gives hg. If the user inputs zero, the user inputs a value of hg, and the program gives the pressure. ------------------------------------------------------------------------------------------------------------

93

Automatic Data Acquisition Using Matlab


Suppose that you were running an experiment, where you wanted to determine the strain (stretch) on a beam as a function of the load on the beam, and that you wanted the results of the experiment (strain vs. load values) to automatically go into your computer. In the old days, you might have had some type of analog output: youd probably read the needle on a gauge, and the gauge would be calibrated to show strain. You would then have to enter the values in a notebook, and plot the data on a graph by hand. To run an experiment and have the data go directly into your computer you need the following: 1) A sensor that changes voltage or resistance as the experimental phenomenon you want to measure changes. For example, say you are measuring the strain on a beam, a strain gauge pasted on the surface of the beam changes electrical resistance as the beam stretches or compresses. The change in resistance of the gauge can then be calibrated to indicate strain. For example, a 10 micro-ohm change indicates a strain of 0.001, etc. If you were running a fluid flow experiment in which you were interested in measuring the speed of some water flow, you might have the current turning a small electric generator, and the amperage of the resulting current could be calibrated to indicate the speed of the current. The two examples listed above give analog outputs, that is, outputs that are changing continuously and smoothly with time. Computers work digitally they require the output from the experiment to be discrete (non-continuous) values made up of ones and zeroes. 2) A way to convert the analog output of your measuring device to digital output that the computer can process. This is done using an analog-to-digital (AD) converter. You can purchase these or build your own. Matlab is configured to easily accept measuring instruments and AD converters from the following companies: Measurement Computing Corporation National Instruments Keithley Instruments Advantech VXI Technology In addition, you can program Matlab to accept other designs, including your own, but this is more involved.

94

AD converters typically require the output from the sensor to the AD converter to be a voltage between a certain range. This might require some circuits to step down or up the voltage entering the AD converter. In addition, the output from the sensor may be a resistance that is changing, which then needs to be converted into a voltage that is changing. For example, a thermistor is a resistor affected by heat, used as a thermometer. In this case, a voltage divider must be used to convert the changing resistance into a changing voltage. The circuit below illustrates a voltage divider:

Vin + R1(Sensor): a varying resistance

R2

Vout

Vout will then vary as R1 (the sensor) varies in resistance. The rule for determining the output voltage based on V1, R1 and R2 is: Vout = Vin R2 R 2 + R1

3) A program to process the ones and zeroes it gets from the AD converter, and convert them into meaningful output. For example, Matlab can process the data gathered during a load-deflection experiment, and present to you a graphical output with deflection vs. load, as well as tabulated values of the data. It should be noted that any measurement instrument needs to be calibrated the changing current or voltage must be translated into a force, pressure, flow rate, etc. If you purchase a ready-made package from one of the companies, this is probably already done for you, but its always a good idea to check the calibration vs. a known quantity.

95

Incidentally, you do not necessarily need Matlab to do automatic data acquisition. The companies that make the AD converters and data acquisition systems may have their own software to process the data. The benefit to using Matlab is in the many features it has available for the processing of acquired data. -----------------------------------------------------------------------------------------------------------Problem A therrmistor has a resistance of 10 ohms, inside a voltage divider circuit. Determine what size resistor is required for R2 if the AD converter needs voltage from 0.1 to 5 volts, and the voltage being supplied is 9V. -----------------------------------------------------------------------------------------------------------Problem Sensors need to be calibrated using known values. In this problem you will use known load values and corresponding voltage readings to determine the relationship between voltage and the load. A strain gauge is connected to a computer, and we wish to calibrate it. The following readings are obtained from known loads: Load: Voltage: 1000 0.1 2000 0.2 3000 0.3 4000 0.42

In order to calibrate the instrument, come up with a polynomial for the load, as a function of voltage, which can be later used to determine the load, given the voltage. -----------------------------------------------------------------------------------------------------------Sample Rate: The number of times per second that the AD converter acquires readings from the sensor is called the sample rate. Its important to pay close attention to the sample rate to ensure you get meaningful data. For example, say that you are measuring the strain on a specimen being gradually loaded with more and more weight. If the weight is being applied at a rate of 100 N/s, and you were interested in capturing increments of 10 N, then the sample rate would need to be at least 10 samples per second. Some phenomena need to be sampled very quickly in order to capture them properly. One example of this is the acquisition of sound. As you know, sound has a frequency, expressed as cycles per second, or hertz (Hz). For example, striking a tuning fork set to 1000 Hz will cause it to vibrate 1000 times per second. Consider the plot below, showing how a 20 Hz signal might look (plot in green). Also on the plot are some black squares, which show the data which would be gathered if samples were taken every 0.1 seconds. The black curve is the curve you might sketch in-between the black squares.

96

You can see that the black curve is nothing like the real green curve, and that to capture the real curve, one might need a sample rate of at least 40 samples per second (twice the frequency of the sound). This form of error, where the sample rate is not fast enough and results in a false frequency is known as alias error.

Automatic Data Acquisition Example 1: Using the soundcard, we can bypass steps 1 and 2 above for a simple demonstration of Matlabs ability to acquire analog data. 97

The microphone on your computer is connected to a sound card that converts the analog signal from the microphone into a digital signal that the computer can understand. We then have a sensor (the microphone) and the AD converter already in-place. If you do not have the Automatic Data Acquisition Toolbox, you will not be able to perform this experiment, but you should understand all the steps anyway. Study and understand the Matlab code below:
%PROGRAM FOR USING SOUND CARD FOR ANALOG INPUT % first instruct Matlab to receive analog data from the sound card % note that analoginput is a built-in function, and 'winsound' % is the sound card. AI = analoginput('winsound') %there are two channels available in the sound card. We will use %the first channel: addchannel(AI,1) %next we specify the sample rate per second. Note that %8000 samples /s is the slowest the sound card samples %Note SampleRate must be spelled exactly sr = 8000; set(AI,'SampleRate',sr) %specify how long we want to take samples for (s) howlong = 2; %note SamplesPerTrigger must be spelled exactly. %It's the number of samples taken every time the program %runs (triggers the software). set(AI,'SamplesPerTrigger',howlong*sr) %start taking data start(AI) data = getdata(AI) %the data will be pairs of time,Voltage plot(data) save sound1.dat data ascii %data saved in sound1.dat, in ascii format %ascii format is readable by other programs %close things up delete(AI)

Thats all there is to it! Using AD converters from the supported manufacturers is just as easy. For example, to acquire data from National Instruments Hardware, you would change the first command: AI = analoginput(nidaq,1) addchannel(AI,1)

98

or for Measurement Computing Corporation: AI=analoginput(mcc,8) addchannel(AI,1) The number after the company abbreviation is hardware specific companies have specific numbers. Consult the Matlab Help and web site for more information on procedures to follow for automatic data acquisition. -----------------------------------------------------------------------------------------------------------Problem/Project This project will involve calibrating sound levels. Using Matlab, you will read sounds made with your voice recorder, and use these sounds to write another Matlab program that will determine if sounds are loud or soft, and give a value for the intensity of the sound. You will not need the data acquisition toolbox, since the microphones sound will be recorded, and the resulting .wav file read using Matlab. The code below reads a .wav file called sountest.wav. The values are for amplitude of the sound wave (sound looks like a sine wave physically, its a series of high and low pressure pulses. Your computer is displaying amplitude values of the wave between +1 and -1). Make a .wav sound file using your computers sound recorder (no need to make it longer than about a second you will be sampling data at a very fast rate, and even one second will give you thousands of readings), and call it sountest1 make sure you save it in your Matlab work directory. Run the program below and study the code carefully. %for reading a .wav file [y,Fs]=wavread('sountest1',100); % y is the amplitude, between 1 and -1. %Fs is the sample rate %the file is sountest1.wav, and the %first 100 samples are read only fprintf('\n Sample Rate %f',Fs) x=[1:1:100]; %make some x points to go with y values, so we can plot plot(x,y) z=std(y); %std deviation of amplitude values c=max(y); %c is the max value of the data d=min(y); %min is the min value of the data fprintf('\n Std deviation %f',z) fprintf('\n Max amplitude %f',c) fprintf('\n Min amplitude %f',d) The project involves two steps: calibration and software development

99

Calibration: Make two sound recordings one whistling softly, and another whistling loudly (again, roughly one second is enough). Once these recordings are made, study their characteristics using the program above (it will need some modification the samples read are probably too few you will need to determine about how many you need by studying the data), and come up with a way in which you can distinguish loud whistles from soft whistles, using the data. Come up with a linear scale from 1 to 100, where 1 is the sound level of your soft whistle, and 100 is the loud whistle. Software Development Come up with a Matlab program that will read a .wav file, and determine if the sound is loud or soft, assigning it a value from 1 to 100, based on your calibration above. ----------------------------------------------------------------------------------------------------------Fourier Transforms Sound data, and many other forms of data, are plagued by unwanted signals referred to as noise. For example, microphones can introduce a background hiss that should not be present. Data acquired could thus be composed of the desired signal as well as unwanted noise. This is not limited to the collection of sound data you may run into this in other data collection schemes. Consider for example the following pure 50 Hz simulated signal

100

The plot above is made with the following Matlab program:


%generates 50 Hz signal %the time points are made. They go up to 0.6 s. %One every 0.001 s - a 1000 Hz signal. t = 0:0.001:0.6; %next we generate a wave of 50 cycles for every one t x = sin(2*pi*50*t) plot(1000*t(1:50),x(1:50)) %we plot only the first 50 points title('50 Hz pure signal') xlabel('time (milliseconds)')

Now we wish to corrupt the signal with some noise. We will do this using a random number generator in Matlab. Consider the code below:
%demonstrates fft %the time points are made. They go up to 0.6 s. %One every 0.001 s - a 1000 Hz signal. t = 0:0.001:0.6; %next we generate a wave of 50 cycles for every one t x = sin(2*pi*50*t) y = x + 2*randn(size(t)); %add some random noise to it plot(1000*t(1:50),y(1:50)) %we plot only the first 50 points title('50 Hz corrupted signal') xlabel('time (milliseconds)')

101

The result is the plot below:

If you compare this with the original plot, you can see that you would be hard-pressed to look at the corrupted signal and know that it came from the 50 Hz signal! Heres where Fourier transforms can help out. Any cyclic data (wave-like), such as sound, can be represented by equations using consisting of sine waves of various frequencies, known as Fourier transforms. Without getting into some very complicated details, Matlab can do this using the fft function, which stands for Fast Fourier Transform (FFT). The Fast Fourier Transform is a very efficient way of performing Fourier transforms. When performing FFT, you must specify the number of points used, and they must be a power of 2. For example, 32, 64, 128, 256, 512, etc are valid. The more points used, the more frequencies can be detected.
%demonstrates fft t = 0:0.001:0.6; x = sin(2*pi*50*t) y = x + 2*randn(size(t)); Y = fft(y,512); %perform fast Fourier transform (FFT)

102

%The power spectrum, a measurement of the power at various frequencies, %is given by the equation below Pyy = Y.* conj(Y) / 512; %Graph the first 257 points (plotting all 512 is unnecessary) % on a meaningful frequency axis. You could get this by trial % and error f = 1000*(0:256)/512; plot(f,Pyy(1:257)) title('Frequency content of y') xlabel('frequency (Hz)')

From the plot you can see that the most power is in the 50 Hz signal, meaning that the most significant signals are those in the 50Hz range. Signals can be made up of more than one frequency. The code below will generate a signal made up of a 50 Hz and a 120 Hz signal. Notice we have simply modified the previous code where x is generated:
%generates 50 Hz with 120 Hz signal %the time points are made. They go up to 0.6 s. %One every 0.001 s - a 1000 Hz signal.

103

t = 0:0.001:0.6; %next we generate a wave of 50 cycles for every one t % x = sin(2*pi*50*t)

x = sin(2*pi*50*t)+sin(2*pi*120*t);
plot(1000*t(1:50),x(1:50)) %we plot only the first 50 points title('50 Hz + 120 Hz pure signal') xlabel('time (milliseconds)')

The plot below shows what is looks like:

We now corrupt the data using a random number generator (the following code is essentially the same as code found in the help section of the documentation, under Fourier Transforms):
t = 0:0.001:0.6; x = sin(2*pi*50*t)+sin(2*pi*120*t); %corrupt it y = x + 2*randn(size(t)); Y = fft(y,512); Pyy = Y.* conj(Y) / 512; f = 1000*(0:256)/512; plot(f,Pyy(1:257))

104

title('Frequency content of y') xlabel('frequency (Hz)') plot(f,Pyy(1:257))

The figure below shows the plot:

Now we perform FFT using the code below:

105

The peaks at 50 and 120 can be clearly seen, representing the two frequencies making up the signal. ---------------------------------------------------------------------------------------------------------Problem Make a Fourier Transform of whistling noises of high and low pitches. Can you detect the frequencies making up the sounds? How do they differ? ---------------------------------------------------------------------------------------------------------

106

CHAPTER 6: OTHER COMPUTER LANGUAGES


Once you learn to program in one language, it becomes much easier to program in another because many of the concepts are the same. We will look now at 3 other languages: C++, Java, Basic, and FORTRAN.

FORTRAN
FORTRAN language was very popular with engineers and scientists in the 1970s-1990s, and its popularity seems to be waning. It is still in use in some companies and institutions some engineering colleges still teach it to its students. There are many, many subroutines (similar to procedures and functions) which have already been written, and which you may need to access in your career. Knowing how to program in FORTRAN can be an asset for your advancement. Please study the code below, which converts polar coordinates to rectangular coordinates using a subroutine (a subroutine is like a procedure in EES, which is called to perform a certain procedure). The letter C denotes a comment, unprocessed by the computer. All operations must start on the 7th space. C the next line specifies what type of numbers you will be working with. C variables rc, tc, xc, yc will be real numbers (with 8 digit accuracy, as opposed to C complex numbers, integers or double precision real numbers with16 digit accuracy) C The variable I will be an integer REAL RC, TC, XC, YC INTEGER I C The next line prints the statement in the apostrophe symbols. Note that you can give C a number to a line in your program. The * denotes an unformatted input (you are not C specifying the way in which you want the statement displayed on the screen). 10 PRINT *,Enter 2 Polar Coordinates, followed by 1 to go on, 0 to stop

C Next we read in the values. The * denote unformatted input. C RC and TC are the polar coordinates we wish to convert READ (*, *) RC, TC, I C If I is ) the program will stop, otherwise it will continue IF ( I .EQ. 0) THEN GO TO 20 END IF C We call the subroutine to do the conversion. In the parentheses we must put what

107

C we are passing to the subroutine (polar coords RC and TC) and what the subroutine C will pass back to the main program ( rectangular coordinates XC and YC). The C variables that you will pass back and forth are sometimes referred to as the arguments. CALL CONVER(RC, TC, XC, YC) C Print to the screen PRINT *,Rectangular Coordinates PRINT *, XC, YC C Lets put in a space in-between entries PRINT * C Go back to line 10 GO TO 10 20 END

C Heres the subroutine C Note that there are four variables next line. They correspond exactly to the variables in C the parentheses in the CALL statement above. In other words, RC corresponds to R, C TC to T, XC to X, and YC to Y. The reason for doing this is to enable the subroutine C to be used by any program, without having to change the names of the variables in the C subroutine. REAL R, T, X, Y X=R * COS(T) Y = R * SIN(T) END Consider also the following FORTRAN commands (Not part of the program above), which you will readily decipher: IF (X.GT.Y) THEN GO TO 20 END IF And also the following code snippet, which loops 100 times, known as a DO Loop: DO 40 I = 1, 100 X=X+1 CONTINUE

40

108

You may also run into the COMMON statement. Recall that when you used a subroutine you had to have an argument list, which lists the variables which will be passed between the main program and the subroutine. The arguments were in parentheses next to the CALL statement, and also on the first line in the subroutine. Instead of listing the variables to be passed between main program and subroutines, a COMMON statement is used instead. The COMMON statement puts the variables in a section of the computers memory that can be accessed by both subroutines and the main program, eliminating the need for the argument list. Consider the code below, which does the same as the previous program: REAL RC, TC, XC, YC COMMON RC, TC, XC, YC INTEGER I PRINT *,Enter 2 Polar Coordinates, followed by 1 to go on, 0 to stop READ (*, *) RC, TC, I IF ( I .EQ. 0) THEN GO TO 20 END IF CALL CONVER

10

C Print to the screen PRINT *,Rectangular Coordinates PRINT *, XC, YC PRINT * GO TO 10 20 END

C Subroutine REAL R, T, X, Y COMMON R, T, X, Y X=R * COS(T) Y = R * SIN(T) END

Some other interesting (and at times quirky) facts about FORTRAN: The letters i, j, k, l, m, n are reserved for integers. For example, if you tried to set ir = 6.7, you would encounter an error, since FORTRAN is expecting an integer. FORTAN must be compiled before running. After writing a FORTRAN program, say it was named flight1, you must type in a command such as fcomp flight 1 (depending on the version of FORTRAN you are using). When you compile a

109

program, the program is converted into machine language, which is the format your computer understands. Compiled languages are typically faster than uncompiled languages. As mentioned earlier, program lines must begin on the 7th space. To use a subroutine not in your program, you may link to another program using some form of link command, that might look something like: link flight1, conver, which would link program flight1 with subroutine conver.

You may wonder why there is a need to distinguish between single and double precision (8 digits vs. 16) why not use double precision all the time? The reason for this is that operations in double precision can take considerably longer to run. This may not be a factor for short calculations, but some programs need to run for millions of loops. In this case, a program might easily run over-night or longer.

110

Java
Java was created in the early 1990s, for use on the internet. It enables programmers to create applets, which are programs attached to web pages. These programs move across the internet to computers accessing a web page with an applet installed. The form you fill out when you purchase something on-line is probably written in Java, as may be any visual effects moving across your screen, or a game you play. Some scientists even use it for computations, as it has the features necessary for numbercrunching, including loops, conditional statements, etc. The difficulties in creating an internet computer language were numerous: it must work on any computer connected to the internet, it must not require any adjustments or installation of other software to run on other computers, and it must be safe from viruses. An interesting thing about Java is that it is an open-source product. You can download it and use it for free from http://java.sun.com , or use any search engine to find it. Here are some code snippets in Java. You can easily decipher them: if (x >= 18) { p = 20*x; } Note the curly brackets show where the loop begins and ends. Try this one: for (int i=1; i<=5;I ++) { x = x+1; } The int tells Java that the variable i is an integer. i will vary from a starting value of 1, and the loop will be executed as long as i is less than or equal to 5. The ++ indicates that the i will be incremented by one each loop. Another sample: x=0 while (x<10) { x = x+1; } Like FORTRAN, after you write a Java program, you must compile it (translate it into machine language).

111

Java is an object oriented language. You will hear this term a lot when dealing with computers. It refers to a language that enables programmers to use pre-made objects, which are procedures and data that are grouped together to perform complicated operations. The author has found that object oriented programming, like entropy, can be quite difficult to define. Typing define object oriented programming into a search engine gives many results most of them undecipherable. Suffice it to say that object oriented programming makes writing complicated programs considerably easier.

112

C++ and Visual C++


C++ is an extremely powerful language. If you are a serious programmer you must know this language. C++ is an improvement of the original C language. What can C++ do? Software programs like Excel are written in C++, as are word processors and most modern computer games. C++ offers programmers extreme flexibility. But this flexibility comes at a price: programming in C++ can be very difficult. Visual C++ is a set of software development tools that help programmers write C++ programs. When you use Visual C++, you are writing C++ programs, but with much of the grunt-work removed. Not that Visual C++ is extremely easy! You will find it much, much more difficult to master than programming in Matlab or EES, because you have so many more features available. In fact, Matlab is written in C language (originally it was written in FORTRAN). C++ is another object-oriented program, and like FORTRAN and Java, must be compiled before running. However, unlike Java, you must purchase a C++ compiler, and there are several of these available. A search for C++ on your search engine will provide a list of these. If you are interested in learning Visual C++ , there are a number of very understandable books available. The For Dummies series is a great way to teach yourself any computer language. C++, Visual C++, FORTRAN, Java, and Matlab are so called high-level programs. Before you can understand what a high-level language is, you have to know that the computer only understands machine language a series of very cryptic looking commands. Machine language is too difficult to work with, so assembly language can be used by programmers wishing to control the computer at its most basic level comparable to taking apart a telephone to make a call. The closer a programming language is to machine language, the lower level it is considered. So, assembly language is considered a low-level language, while C++ , FORTRAN, Java, Matlab are considered high-level languages. Matlab is a higher level language than C++. Since Matlab is written in C language, it is more removed from machine language than C or C++. Lets look at a Visual C++ program. You will see much in common with the languages we have been studying. // sample program // note that a comment is made by two/ marks. #include <iostream.h> // this line makes available to the program a function called iostream // that most programs in C++ need in order to run and have input-output.

113

// the file iostream is called a header file, because it usually goes at the head of the // program. The .h indicates its a header file. using namespace std; / * another format for the comment the comment will finish at the next slash mark followed by the asterisk. Visual C++ has what is called a standard library of functions useful to a programmer. There is a very large number of these, and the line above is put in to avoid problems which might arise if you use one of these names in your program. We end the comment with the following */ void main( ) { /* When you run a program, C++ needs to know where to start computing. Computation will start after the curly bracket { . The end of the program will have another one} At times, you might see this statement as: int main( ) { */ int x = 1; double y = 25.4321678; float pi = 3.14159f; int z; /* above are several types of variables in C++, and here are three of them. The first one defines x as an integer, and assigns it a value of 1. The second one defines y as a double precision number, accurate to 15 decimal digits. The range of values stored is much wider than this from 1.7 x 10^(-308) to 1.7 x 10^(308), positive and negative, accurate to 15 digits. the third one defines a number with 7 digit accuracy, similar to the real seen in FORTRAN. The last statement defines z as an integer, without giving it any value ALL VARIABLES MUST BE DEFINED IN C++ !! Note that program lines end with a semi-colon ; */ if( x < 10) { z = 15; } // you can figure the above out! if(x = = 10)

114

{ z = 20; } // you must use the double equal sign here, or else C++ will set x to 10 for ( i = 1; i < = 15; i++) { sum = sum + 1; } /* The loop gets executed starting with i = 1, and continues as long as i is less than or equal to 15. i is incremented in steps of 1 (thats what the ++ means). The curly brackets denote the beginning and end of the loop. Plese note that there is an error here, in that variables i and sum need to be defines at the beginning of the program, with statements like int sum and int i */ while (x < 10) { x = x + 1; } /* you know this one! The expression for x could have been written as x++ to save 0.2 seconds of typing. */ } / / curly bracket ends main program

You should understand everything above.

115

APPENDIX TO DATA ACQUISITION SECTION More data acquisition The following M-file reads a temperature sensor. The output from the sensor/AD converter is in Volts, between + and 0.5 V. The purpose of the program is to calibrate the sensor the known temperature will be input as the program runs, and then a plot made of load vs. voltage. Once the relationship between temperature and voltage is known, any future voltage readings can be converted to temperature. This program is modified from a program found in the Matlab website, and is untested. There may be minor bugs.
% Thermistor Calibration clear; % Initialize Matlab Data Acquisition Engine % % % % % The sensor will be sampled at 1000 samples per second. 100 samples will be taken. The engine is set up to take one channel of analog input data, with a range between +/- 0.05 V.

ai=analoginput('nidaq',1); % (Creates analog input module called ai in Matlab)

chan=addchannel(ai,1); % (Sets up Channel 1 for the thermistor output)

set(chan,'InputRange',[-.05 .05]); % % (Sets the range for channel 1). Note this was unspecified in the previous example.

set(ai,'samplerate',1000); % (Sets the sample rate to 1000 samples/s)

set(ai,'samplespertrigger',100); % (Causes the engine to take 100 samples when takes data)

set(ai,'BufferingConfig', [10 40]) % Set the bufferingConfig

116

%such that the product of the two numbers exceed samples per %trigger. Data collected is stored in RAM, so must make room %for it in the buffer. fle=input('\nEnter File Name for Saving Data: ','s'); % (User inputs file name to save test data)

%create figure (creates a window at the upper left of screen for plot) set(0,'Units','pixels'); scnsize=get(0,'Screensize'); bdwidth=5; topbdwidth=30; pos1=[bdwidth,1/2*scnsize(4)+bdwidth,scnsize(3)/22*bdwidth,scnsize(4)/2.5-(topbdwidth+bdwidth)]; figure('Position',pos1); pause; %open the file to receive the data fid=fopen(fle,'w');%Opens file named in previous command title=' "Thermistor Calibration" ';%This title will be placed in file fprintf(fid,'%s\n',title);%Title is written to file a='y';% Initialize variable a i=0;%Initialize variable i a='r';%Initialize the variable a while a~='d'& a~='t' %This will allow program user to decide whether to % keep taking data. If user presses d, program goes on, if enters t % program ends. User will be prompted after each voltage, temperature % reading is input. a=input('\nEnter d to take Data, t to Terminate: ','s'); end;

%start the loop to take the data

117

while a=='d' i=i+1; start(ai); % (Starts engine with immediate triggering

volt=getdata(ai); %Takes data from engine and puts in variable volt

temperature=input('\nEnter Weight on Load Cell: '); % (Get user input of temperature being read)

w(i)=temperature; vaves=mean(volt);%vaves is the average voltage reading v(i)=1000*vaves;%v is load cell voltage in mV %Print to Screen display(['Temperature= ' num2str(w(i)) ' out(mV)='num2str(v(i))]); %Show data on a plot %create the plot clf;%clears out the contents of the figure window axes('position',[.3,.35,.5,.5]);%locates plot within window hold; plot(w,v,'*r');%puts data on plot xlabel('Temperature','Fontsize',8); ylabel('Thermistor Voltage - mV','Fontsize',8); TITLE('Thermistor Output','Fontsize',9); a='r'; while a~='d'& a~='t' a=input('\nEnter d to take Data, t to Terminate: ','s'); end; Cell

118

% end title2='

(User decides whether to take more data)

temperature-(F)

vldcl-(mV) ';%Column titles for output file

fprintf(fid,'%s\n',title2);%Print column titles to file %print data to file for j=1:i fprintf(fid,'%8.4f',j,w(j),v(j));%Print test data to file fprintf(fid,'\n'); end fclose(fid);%close file

119

S-ar putea să vă placă și