Program design and algorithm development are presented, along with many examples from a wide range of familiar scientific and engineering areas. Best-selling author Delores Etter introduces engineering students to general problem-solving and design techniques through a five-step process that uses MATLAB. Each chapter is organized around a specific application - drawn from a variety of engineering disciplines - that illustrates a particular MATLAB capability. Recent developments in MATLAB to advance programming are described using realistic examples in order to prepare students for larger programming projects.
In addition, a large number of exercises, tips, and solutions mean that the course can be followed with or without a computer. The development of MATLAB programming and its use in engineering courses makes this a valuable self-study guide for both engineering students and practicing engineers.
The terminology, syntax, and the use of the programming language are well defined, and the organization of the material makes it easy to locate information and navigate through the textbook. The text consists of 11 chapters. It will cover some of the new features, but won't cover any of the advanced features in-depth.
Like the previous edition, it will be specifically geared towards the needs of engineering students who are expected to use MATLAB to model and solve real engineering problems. The book covers concepts such as: functions, algebra, geometry, arrays, vectors, matrices, trigonometry, graphs, pre-calculus and calculus. It then delves into the Matlab language, covering syntax rules, notation, operations, computational programming, and general problem solving in the areas of applied mathematics and general physics.
The first volume covers concepts such as: functions, algebra, geometry, arrays, vectors, matrices, trigonometry, graphs, pre-calculus and calculus.
It then delves into the Matlab language, covering syntax rules, notation, operations, computational programming. The second volume illustrates the direct connection between theory and real applications. Each chapter reviews basic concepts and then explores those concepts with a number of worked out examples. Once you finish debugging it and it executes successfully try modifying it. What is the square root of x? What is the cosine of the square root of x?
What is the square root of y? Also, when nec- name. Hence, it also should not be used as an index or as a variable name. Give an example of how you have used complex numbers in your studies of mathematics and the sciences up to this point in your education. Solutions to many of the exercises are in Appendix D. The last part of this chapter and the next chapter logspace functions. In a sense, the art of programming under gravity The colon operator. Examples of invalid names why?
In other Limit of a sequence 58 words, a scalar is a 1-by-1 array—an array with a single row and a single column The basic for which, of course, is an array of one item. Many programmers write variable names in lowercase except for the first statement This style is known as camel caps, the uppercase let- construct Some programmers prefer to separate if-else statement..
Logical operators You must not use capi- Multiple ifs versus elseif Nested ifs Enter the command clear and then rerun the compound interest program see Section 1.
Now numbers You should see a list of variables as follows: Summary You can use or change their values at any stage during the session. The function ans returns the value of the last expression evaluated but not assigned to a variable. The command whos lists the size of each variable as well: Name Size Bytes Class balance 1x1 8 double interest 1x1 8 double rate 1x1 8 double Each variable here occupies eight bytes of storage.
A byte is the amount of com- puter memory required for one character if you are interested, one byte is the same as eight bits. The Class double means that the variable holds numeric values as double-precision floating-point see Section 2. The command clear removes all variables from the workspace.
A particular variable can be removed from the workspace e. More than one variable can also be cleared e. Separate the variable names with spaces, not commas. When you run a program, any variables created by it remain in the workspace after it runs. This means that existing variables with the same names are over- written. The Workspace browser on the desktop provides a handy visual representation of the workspace. You can view and even change the values of workspace vari- ables with the Array Editor.
To activate the Array Editor click on a variable in the Workspace browser or right-click to get the more general context menu. From the context menu you can draw graphs of workspace variables in various ways. For example, the following statements can be saved in myconst. A matrix is a rect- angular object e.
A vector is a special type of matrix, having only one row or one column. Vectors are called lists or arrays in other programming languages. MATLAB handles vectors and matrices in the same way, but since vectors are easier to think about than matrices, we will look at them first. We will also use the term array generally, with vector and matrix referring to the one-dimensional 1D and two-dimensional 2D array forms.
These are all examples of the explicit list method of initializing vectors. Exercises 2. Make sure to leave out the semicolon so that you can see the list. Also, make sure you hit Enter to execute the command. Under the head- ing Size you will see that x is 1 by 5, which means 1 row and 5 columns. You will also see that the total number of elements is 5.
Take the space between the minus sign and 15 to see how the assignment of x changes. An empty array may be used to remove elements from an array see Sec- tion 2.
The function logspace can be used to generate logarithmically spaced data. It is a logarithmic equivalent of linspace. If the last number in this function call is omitted, the num- ber of values of y computed is by default Thus, the logspace function produces a set of points with an interval between them that increases linearly with y.
The variable yy was introduced for two reasons. The first was to generate a vector of the same length as dy. The second was to examine the increase in the interval with increase in y that is obtained with the implementation of logspace. Each has one row and several columns. To generate the column vectors that are often needed in mathematics, you need to transpose such vectors—that is, you need to interchange their rows and columns.
Note that x itself remains a row vector. Try the following: 1. This gives you a row vector of seven random num- bers. Enter r 3. This will display the third element of r. The numeral 3 is the subscript. Enter r This should give you the second, third, and fourth ele- ments. What about r and r [1 7 2 6]? You cre- ate a matrix just as you do a vector, except that a semicolon is used to indicate the end of a row.
Generate the table of angles and sines as shown above. Select all seven rows of numerical output in the Command Window, and copy the selected output to the Editor. You can then edit the output, for example, by inserting text headings above each column this is easier than trying to get headings to line up over the columns with a disp statement. The edited output can in turn be pasted into a report or printed as is the File menu has a number of printing options. Another way of capturing output is with the diary command.
The command diary filename copies everything that subsequently appears in the Command Window to the text file filename. Stop recording the session with diary off Note that diary appends material to an existing file—that is, it adds new infor- mation to the end of it. It is typically written in what is called pseudo- code—that is, statements in English, mathematics, and MATLAB describing in detail how to solve a problem.
A structure plan may be writ- ten at a number of levels, each of increasing complexity, as the logical structure of the program is developed. A first-level structure plan might be a simple statement of the problem: 1.
Initialize Fahrenheit temperature 2. Calculate and display Celsius temperature 3. Stop Step 1 is pretty straightforward. Step 2 needs elaborating, so the second-level plan could be something like this: 1. Initialize Fahrenheit temperature F 2. Display the value of C 4.
Stop There are no hard and fast rules for writing structure plans. The essential point is to cultivate the mental discipline of getting the problem logic clear before attempting to write the program. The top-down approach of structure plans means that the overall structure of a program is clearly thought out before you have to worry about the details of syntax coding. This reduces the number of errors enormously.
The results were found to be correct and hence this simple script is, as such, validated. The essence of any structure plan and, hence, any computer program can be summarized as follows: 1.
Input: Declare and assign input variables. Operations: Solve expressions that use the input variables. Output: Display in graphs or tables the desired results. Air resistance is ignored. We would like to compute the value of s over a period of about The structure plan for this problem is as follows: 1. This plan may seem trivial and a waste of time to write down.
Yet you would be surprised how many beginners, preferring to rush straight to the computer, start with step 2 instead of step 1. It is well worth developing the mental disci- pline of structure-planning your program first. You can even use cut and paste to plan as follows: 1. Paste a second copy of the plan directly below the first.
Finally, paste all the translated MATLAB statements into the Command Window and run them or you can just click on the green triangle in the toolbar of the Editor to execute your script. If necessary, go back to the Editor to make corrections and repaste the corrected statements to the Command Window or save the program in the Editor as an M-file and execute it. This is called an array op- eration and is different from squaring the vector itself, which is a matrix operation, as we will see later.
You might want to save the program under a helpful name, like throw. This way, the plan reminds you what the program does when you look at it again after some months. After you block selected text, right-click to see the context menu.
To comment the text, scroll down to Comment, point, and click. Expressions are constructed from a variety of things, such as numbers, variables, and operators. First we need to look at numbers. For example, 1. This is also called floating-point notation. The number has two parts: the mantissa, which may have an optional decimal point 1. Mantissa and exponent must be separated by the letter e or E. The mantissa is multiplied by the power of 10 indicated by the exponent.
Note that the following is not scientific notation: 1. On computers using standard floating-point arithmetic, numbers are repre- sented to approximately 16 significant decimal digits. The relative accuracy of numbers is given by the function eps, which is defined as the distance between 1. Enter eps to see its value on your computer.
As an exercise, enter the following numbers at the command prompt in scien- tific notation answers follow in parentheses : 1. More information on data types can be found in the Help index. Precedence Operator 1 Parentheses round brackets 2 Power, left to right 3 Multiplication and division, left to right 4 Addition and subtraction, left to right MATLAB also supports signed and unsigned integer types and single-precision floating-point, by means of functions such as int8, uint8, single, and the like.
However, before mathematical operations can be performed on such types, they must be converted to double precision using the double function. The arithmetic operations on two scalar constants or variables are shown in Ta- ble 2. Operators operate on operands a and b in the table.
Left division seems a little curious: Divide the right operand by the left operand. However, matrix left division has an entirely different meaning, as we will see later.
The precedence rules for the operators in Table 2. Note that parentheses have the highest precedence. Note also the difference between parentheses and square brackets. The former are used to alter the precedence of operators and to denote subscripts, while the latter are used to create vectors. Answers are in parenthe- ses. The value 1 is added to each element of the vector In this context, the addition is called an array operation because it operates on each element of the vector array.
Array operations are discussed below. Operator Description. They are sometimes called array or element-by-element operations because they are per- formed element by element. For example, a. You will have seen that a. Now try [2 3 4]. The ith element of the first vector is raised to the power of the ith element of the second vector.
The period dot is necessary for the array operations of multiplication, division, and exponentiation because these operations are defined differently for matrices; they are then called matrix op- erations see Chapter 6. When array operations are applied to two vectors, both vectors must be the same size!
Array operations also apply between a scalar and a nonscalar. Check this with 3. This property is called scalar expansion. Multiplication and division operations between scalars and nonscalars can be written with or without the period i.
Answer: [0 -2 3] 2. Assignment always works in this direction. Note that the object on the left-hand side of the assign- ment must be a variable name. This is useful for suppressing irritating output of interme- diate results or large matrices. Statements may involve array operations, in which case the variable on the left-hand side may become a vector or a matrix.
However, it is help- ful to think of commands as changing the general environment in some way, for example, load, save, and clear. Statements do the sort of thing we usu- ally associate with programming, such as evaluating expressions and carrying out assignments, making decisions if , and repeating for. Functions return with calculated values or perform some operation on data, such as sin and plot.
Let us again consider, as an example, the calculation of compound interest. The following program comp. This process is called formula vectorization. The operation in the statement de- scribed in bullet item 1 is such that every element in the vector B is determined by operating on every element of vector A all at once, by interpreting once a single command line. See if you can adjust the program comp. Hint: use a vector for n: [1 5 10 15 20]. The numerical answers are in parentheses.
The answers are in paren- theses. Can you spot the errors in the following expression? You need to think through the process care- fully. For example, convert 5 acres to hectares, given that an acre is square yards, a yard is 36 inches, an inch is 2.
The best approach is to develop a formula to convert x acres to hectares. You can do this as follows. Convert 75 kilograms to pounds. Convert 40 psi to kPa. Convert 6. You can also use disp to display a message enclosed in apostrophes called a string. If we want to display a string, we create it; that is, we type a message between apostrophes. Note that the last space before the second apostrophe is part of the string.
The command more on enables paging of output. This is very useful when dis- playing large matrices, for example, rand ,7 see help more for details. You can begin your search for infor- mation by clicking the question mark at the top of the desktop to open the help documents.
Then search for fopen, a utility which allows you to open a file. Scroll to the bottom of the page in the help manual on this topic and find the following list of functions: fclose, feof, ferror, fprintf, fread, fscanf, fseek, ftell, fwrite. Search for input in the help manual to learn more about this function that is used in a number of examples in this text.
Of course, the simplest input of data is the assignment of values to variables in a program of commands. However, if the integer is too large, it is displayed in scientific notation with five significant digits— is displayed as 1.
Check this by first entering at the command line and then If the value x is in the range 0. Check this by entering the following numbers at the prompt on separate lines : 0.
You can change from the default with variations on the format command, as follows. If you want values displayed in scientific notation floating-point form whatever their size, enter the command format short e All output from subsequent disp statements will be in scientific notation, with five significant digits, until the next format command is issued. Enter this com- mand and check it with the following values: 0. If you want more accurate output, you can use format long e. This also gives scientific notation but with 15 significant digits.
Use format long to get fixed-point notation with 15 significant digits. Use format bank for financial calculations; you get fixed point with two dec- imal digits for cents. Suppress irritating line feeds with format compact, which gives a more compact display. Use format hex to get hexadecimal display.
Use format rat to display a number as a rational approximation ratio of two integers. Note that even this is an approximation! In certain appli- cations this is a convenient way of displaying matrices. The command format by itself reverts to the default format.
In this example, the common scale factor is , so the elements displayed must all be multiplied by it to get their proper value—for example, for the second element 1. Taking a factor of out of the third element 1e-4 leaves 1e-7, which is represented by 0. In this section we look at a new feature: repetition. We will first look at some examples of its use, followed by explanations. For starters, enter the following group of statements on the command line. The disp statement is repeated five times, three times, and not at all.
This is an iterative repetitive procedure that refines an initial guess. Here is the structure plan: 1. Initialize a 2. Most computers and calculators use a similar method internally to compute square roots and other standard mathematical functions. Run the following program to generate a list of n and n!
You had better leave out the disp statement! Or you can move it from above the end command to below it. The following example also highlights a problem that sometimes occurs when computing a limit. The question is this: What is the limit of this sequence as n gets indefinitely large? If we try to compute xn directly, we can get into trouble, because n! Each time through the loop it will contain the next element of the vector j :k or j :m:k, and statements there may be one or more are carried out for each of these values.
This value is called the iteration or trip count. Note that if the iteration count is negative, the loop is not executed. It is basically a counter. In fact, if the index does appear explicitly in statements, the for can often be vectorized more details on this are given in Section 2.
A simple example of a more efficient faster program is as follows. In this case i is assigned as a vector hence, this change vectorizes the original program. You may have noticed that the Editor does this for you auto- matically with a feature called smart indenting. If you leave them out you will get an error message. Nothing will happen until you do so. The index moves through each element of the vector in turn, providing a neat way of processing each item in a list.
Other forms of the for loop as well as the while loop will be discussed in Chapter 8. There are situations where a for loop is essential, as in many of the examples in this section so far. If you have written a for loop that involves the index of the loop in an expression, it may be possible to vectorize the expression, making use of array operations where necessary, as the following examples show.
Thus, t0 records when the calculation starts. The function etime returns the time in seconds elapsed between its two argu- ments, which must be vectors as returned by clock. On a Pentium II, it returned about 3. If you have a faster PC, it should take less time. Now try to vectorize this calculation before looking at the solution. Of course, the computation time in these ex- amples is small regardless of the method applied.
However, learning how to improve the efficiency of computation to solve more complex scientific or en- gineering problems will be helpful as you develop good programming skills. More details on good problem-solving and program design practices are in- troduced at the end of this chapter and dealt with, in more detail, in the next. Series with alternating signs are a little more challenging. You should get 0.
Not bad. For ex- ample, prod 1:n will find n! Time both versions in each case. Repeat a few times—cut and paste from the Command History window make sure that a new r is generated each time. The if construct, which is fundamental to all com- puting languages, is the basis of such decision making. The relational operators are shown in Table 2. If the expression evaluates to 0, it is regarded as false; any other value is true.
This is not generally recommended; the if statement is eas- ier to understand for you or a reader of your code if condition is a logical expression. A single zero element in a vector or matrix renders it false. The value 1 for true is therefore assigned to x. What about g? Try other values, including 0 and some negative values.
Most banks offer differential interest rates. The Random Bank goes one step further and gives you a random amount in your account to start with! In general, the elseif clause is used: if condition1 statementsA elseif condition2 statementsB elseif condition3 statementsC It works as follows: 1.
If it is true, statementsB are executed, followed by the statement after end. In this way, all conditions are tested until a true one is found. If none of the conditions is true, statements after else are executed. Arrange the logic so that not more than one of the conditions is true. There can be any number of elseifs, but at most one else. It is good programming style to indent each group of statements as shown. Note the double equal sign in the test for equality; see Chapter 5 for more on logical operators.
This saves a lot of computing time and is easier to read if the if construct is in a loop that is repeated often. When designing the logic, you need to make sure that one and only one of the conditions will be true at any one time. However, whatever the value of bal, this condition will always be true.
Can you see why? This is called nesting and should not be confused with the elseif ladder. You have to be careful with elses. In general, else belongs to the most recent if that has not been ended.
The correct positioning of end is therefore very important, as the next example demonstrates. Suppose you want to compute the solution to a quadratic equation.
Your program could contain the following nested ifs The result is that else belongs to the first if instead of to the second one. Division by zero is therefore guaranteed instead of prevented! You may be wondering if for statements enclosing ifs can be vectorized. The answer is yes, courtesy of logical arrays. Discussion of this rather interesting topic is postponed until Chapter 5. In this example it is used to decide whether a random integer is 1, 2, or 3 see Section 5.
However, it is useful to know what they are since the square root of a negative number may come up as a mistake if you are trying to work only with real numbers. The imaginary part of a complex number may also be entered without an asterisk, 3i. Some functions are specific to complex numbers.
If z is a complex number, real z , imag z , conj z , and abs z all have the obvious meanings. It can be accessed through the Help button? In other words, it is a program. The statements are carried out when the script file name is entered at the prompt in the Command Window.
A script file name must have the. Script files are therefore also called M-files. The output from the script will then appear in the Command Window. Only the first 63 characters are significant. All variables created during a session remain in the workspace until removed with clear. The command who lists the variables in the workspace; whos gives their sizes. Clicking a variable in it invokes the Array Editor, which may be used to view and change variable values.
Elements are sep- arated by spaces or commas. Rows are separated by semicolons. The colon operator is used to generate vectors, with elements increasing de- creasing by regular increments decrements.
Vectors are row vectors by default. A sub- script may itself be a vector. Subscripts always start at 1. The default numeric type is double precision. All mathematical operations are carried out in double precision. They operate according to rules of precedence. A semicolon after an expression suppresses display of its value. The array operations of multiplication, right and left division, and exponentiation are indicated by.
They may be used to evaluate a formula repeatedly for some or all of the elements of a vector. This is called vectorization of the formula. If the index of a for statement is used in the expression being repeated, the expression can often be vectorized, saving a great deal of computing time.
Any expression that evaluates to zero is regarded as false. Any other value is true. The elseif ladder is a good way to choose between a number of options, only one of which should be true at a time.
Answer: 3. The volume of a tank is given as 2 gallons and 4 pints. Write a script that inputs this volume in gallons and pints and converts it to liters.
Answer: Now try to add tangents in the fourth column. Try some variations of the format command. Answer: 10, 2. The marks are out of Write a statement to find and display the average mark.
Try it on the following: 5 8 0 10 3 8 5 7 9 4 Answer: 5. Can you do even better by vectorizing the code? Can you figure out what it is? Now rewrite the script using vectors and array operations. Draw up a table of the values of i, j, and m to show how they change while the script executes.
Check your answers by running the script. Compute the value of I. Answer: 0. Write a program that enters the following five consumptions into a vec- tor and uses a for loop to calculate and display the total charge for each one: , , , , Write a program to compute and print the balance each month for a year. Write a program that uses a for loop to compute the balance after a year of compounding interest in this way.
Answer: Values in the last row of output should be 12, 0. Write a program to compute and display the population every ten years from to Try to plot a graph of the population against time as well.
Use the built-in function log for the natural logarithm ln. A Supplementary material 81 b Use your program to find out by trial and error the smallest monthly payment that will pay off the loan this side of eternity.
We will consider the design of your own toolbox to be included Harmonic among those already available with your version of MATLAB, such as Simulink, oscillators In the first part of this chapter we discuss the design process. In the second part we examine the structure plan—the detailed description of the algorithm to be implemented. We will consider relatively simple programs. However, the pro- cess described is intended to provide insight into what you will confront when you deal with more complex engineering, scientific, and mathematical prob- lems during the later years of your formal education, your life-long learning, and your continuing professional education.
In the third part we introduce the basic construct of a MATLAB function to help you develop more sophisticated programs. To be sure, the examples examined so far have been logically simple. It is very important to learn how MATLAB does the arith- metic operations that form the basis of more complex programs. To design a successful program you need to understand a problem thoroughly and break it down into its most fundamental logical stages.
In other words, you have to develop a systematic procedure or algorithm for solving it. There are a number of methods that may assist in algorithm development. In this chapter we look at one, the structure plan. Its development is the primary part of the software or code design process because it is the steps in it that are translated into a language the computer can understand—for example, into MATLAB commands.
There are numerous toolboxes available through MathWorks among others on a variety of engi- neering and scientific topics. A great example is the Aerospace Toolbox, which provides reference standards, environmental models, and aerodynamic coef- ficients importing for advanced aerospace engineering designs. In your working directory, e.
Certainly, you want to be sure that the tools you save are reasonably well writ- ten i. What does it mean to create well-written programs? The goals in designing a software tool are that it works, it can easily be read and understood, and, hence, it can be systematically modified when required. For programs to work well they must satisfy the requirements associated with the problem or class of problems they are intended to solve. The specifications i. That is, all options should be usable without error within the limits of the specifications see Figs.
Thus, it is useful to decompose major tasks or the main program into subtasks or sub- programs that do specific parts of it. Each subtask should be designed so that it can be evaluated in- dependently before it is implemented in the larger scheme of things i. A well written code, when it works, is much more easily evaluated in the testing phase of the design process. If changes are necessary to correct sign mistakes and the like, they can be easily implemented. One thing to keep in mind when you add comments to describe the process programmed is this: Add enough comments and references so that a year from the time you write the program you know exactly what was done and for what purpose.
Note that the first few comment lines in a script file are displayed in the Command Window when you type help followed by the name of your file file naming is also an art.
The design process1 is outlined next. The steps may be listed as follows: Step 1 Problem analysis. The context of the proposed investigation must be es- tablished to provide the proper motivation for the design of a computer program.
The designer must fully recognize the need and must develop an understanding of the nature of the problem to be solved.
Step 2 Problem statement. Develop a detailed statement of the mathematical problem to be solved with a computer program. Step 3 Processing scheme. Define the inputs required and the outputs to be produced by the program. Step 4 Algorithm. Design the step-by-step procedure in a top-down process that decomposes the overall problem into subordinate problems.
The sub- tasks to solve the latter are refined by designing an itemized list of steps to be programmed. This list of tasks is the structure plan and is written in pseudo-code i.
The goal is a plan that is understandable and easily translated into a computer language. Step 5 Program algorithm. Translate or convert the algorithm into a computer language e. Step 6 Evaluation. Test all of the options and conduct a validation study of the program. The objective is to determine that the sub- tasks and the overall program are correct and accurate.
The additional debugging in this step is to find and correct logical errors e. Step 7 Application. Solve the problems the program was designed to solve. If the program is well designed and useful, it can be saved in your working directory i. Let us consider the projectile problem examined in first-semester physics. It is assumed that engineering and science students understand this problem if it is not familiar to you, find a physics text that describes it or search the Web; the formulas that apply will be provided in step 2.
In this example we want to calculate the flight of a projectile e. We want to determine the trajectory of the flight path and the horizontal distance the projectile or object travels before it hits the ground. Let us assume zero air resistance and a constant gravitational force acting on the object in the oppo- site direction of the vertical distance from the ground.
We want to determine the time it takes the projectile, from the start of motion, to hit the ground, the horizontal distance traveled, and the shape of the trajec- tory.
In addition, we want to plot the speed of the projectile versus the angular direction of this vector. We need, of course, the theory or mathematical ex- pressions that describes the solution to the zero-resistance projectile problem in order to develop an algorithm to obtain solutions to it.
Step 2. The mathematical formulas that describe the solution to the projectile problem are provided in this step. Then the maximum values of the altitude and the range are computed along with their respective arrival times. Step 3. The outputs are the range and time of flight, the maximum altitude and the time it is reached, and the shape of the trajectory in graphical form. The algorithm and structure plan developed to solve this problem are given next as a MATLAB program, because it is relatively straightforward and the translation to MATLAB is well commented with details of the approach applied to its solution i.
This plan, and M-file, of course, is the summary of the results developed by trying a number of approaches during the design process, and thus discard- ing numerous sheets of scratch paper before summarizing the results! There are more explicit examples of structure plans for your review and investigation in the next section of this chapter. Keep in mind that it was not difficult to enumerate a list of steps associated with the general design process, that is, the technical problem solving.
However, it is certainly not so easy to imple- ment the steps because they draw heavily on your technical-solution design experience. Hence, we must begin by studying the design of relatively simple programs like the one described in this section. Define the input variables. Calculate the range and duration of the flight.
Compute the trajectory. Display in the Command Window and on figures the ouput. Steps 6 and 7. The program was evaluated by executing a number of values of the launch angle and launch speed within the required specifications. The an- gle of 45 degrees was checked to determine that the maximum range occurred at this angle for all specified launch speeds.
This is well known for the zero air resistance case in a constant g force field. How can you find additional examples of MATLAB programs good ones or otherwise to help develop tools to solve your own problems? There are also many examples of use- ful scripts that are placed on the Web for anyone interested in them. This responsibility holds for all tools applied by the engineer and the scientist. Hence, it is very important just as in using a laboratory apparatus that users prove to themselves that the tool they are using is indeed valid for the problem they are trying to solve.
To check that it works, type each line in the Command Window followed by Enter. Note the position of each graphic; location is determined by the three integers in the subplot function list of arguments. Search Help via the question mark? A function M-file is similar to a script file in that it also has a. However, a function M-file differs from a script file in that a function M-file communicates with the MATLAB workspace only through specially designated input and output argu- ments.
Functions are indispensable tools when it comes to breaking a problem down into manageable logical pieces. Short mathematical functions may be written as one-line inline objects. This capability is illustrated by example in the next subsection. Further details on writing functions are provided in Chapter The construction of a function file starts with the declaration of a function command. This is followed by the formula that is the function of interest that you wish to substitute a particular value of x to get the corresponding value of y.
The structure plan for the evaluation of a particular algebraic function is as follows: 1. It was saved as f. After saving it, it was used as follows in the Command Window.
We want to determine the two roots of this equation, i. One way of dealing with this problem is to apply the known solutions of the quadratic equation. Start 2. It is a useful exercise to test all possibilities to evaluate whether or not this function successfully deals with all quadratic equations with constant coefficients.
The purpose of this example was to il- lustrate how to construct a function file. Note that the only variables in the Workspace are the coefficients a b c. The variables defined and needed in the function are not included in the Workspace. Hence, functions do not clutter the Workspace with the variables only needed in the function itself to execute the commands within it. Carry out the plan by sketching the construction: 1.
Draw two perpendicular x- and y-axes 2. Draw the points A 10, 0 and B 0, 1 3. While A does not coincide with the origin repeat: Draw a straight line joining A and B Move A one unit to the left along the x-axis Move B one unit up on the y-axis 4. Stop 3. Display M 4. Stop a Work through the structure plan, sketching the contents of M and N during execution. Give the output.
Test it on the data in Exercise 2. Use the structure plan in Section 3. Your script should be able to handle all possible values of the data a, b, and c. Adjust your script so that it can also find complex roots.
However, it is good for the development of your programming skills to do it the long way, as in this exercise. Plot y versus t for t from 0 to 10 in increments of 0. Hint: Develop a solution procedure by working backwards through the problem statement. Starting at the end of the problem statement, the solution procedure requires the programmer to assign the input vari- ables first followed by the execution of the formula for the amplitude and ending with the output in graphical form.
This shape is called a uniform catenary. However, more interesting problems in science and engineering data This chapter introduces you to the more common Exercises In addition, you may wish to import data to be plotted or operated on mathematically, and export data for future use.
It also discusses the exporting of data to files in your work directory for later use with MATLAB or with other software tools. A short list of some of the more common ones follows. Use helpwin at the command line to see a list of categories of functions, with links to descriptions of the functions.
Note that if the argument of a function is an array, the function is applied element by element to all the values in the array, e. It is also, to some extent, expected that you already know, from your first courses in mathematics and science, something about these functions.
One way to ex- amine these functions is to plot them. For example, do the following exercise for all functions of the assigned variable x, as illustrated next. Note how the hours, minutes and seconds are left- filled with zeros if necessary. Let us consider the arc-cosine, the arc-sine and the arc-tangent functions, i. If you specify x, i. To provide an answer, the following M-file script was created and executed.
The graphical comparison of the computed results is illustrated in Fig. Valentine - September The process of moving data between MATLAB and disk files is called importing from disk files and exporting to disk files. Data are saved in disk files in one of two formats: text or binary. Binary format is more efficient in terms of storage space required.
You can use tabs instead of spaces by specifying the -tabs qualifier instead of -ascii. If you save character arrays strings in this way, the ASCII codes of the characters are written to the file. If the array A has been saved in myData. You can create it in a text editor, or it could be created by any other program that exports data in ASCII format. Write a script to input a length in meters which may have a dec- imal part and convert it to yards, feet and inches.
Check: 3. The program displays every member xn computed. Adjust it to display only every 10th value of xn. Hint: the expression rem n, 10 will be zero only when n is an exact multiple of Use this in an if statement to display every tenth value of xn. Write a script which inputs a number of minutes and converts it to hours and minutes. Now write a script to convert seconds into hours, minutes and seconds. Try out your script on 10 seconds, which should convert to 2 hours, 46 minutes and 40 seconds.
The plan must specify the number and type of all notes and coins in the change, and should in all cases give as few notes and coins as possible. If you are not familiar with dollars and cents, use your own monetary system. It carries a uniformly distributed load of W per unit length, and there is a tension T along the x-axis. The topic is so useful and, hence, important that it deserves Operator a chapter of its own. It should re- Using any and all.. Enter the following statements: Summary Can you see why 0 0 0 1 0 is returned?
When a vector is involved in a logical expression, the comparison is carried out element by element as in an arithmetic operation. If the comparison is true for a particular element of the vector, the resulting vector, which is called a logical vector, has a 1 in the corresponding position; otherwise it has a 0.
The same applies to logical expressions involving matrices. You can also compare vectors with vectors in logical expressions. The following script plots the graph, shown in Fig. Element-by-element multiplication by y with.
0コメント