Baixe MATLAB Programming - David Kuncicky e outras Notas de estudo em PDF para Engenharia Elétrica, somente na Docsity!
Contents
Section 1
Engineering Problem Solving
Engineering often involves applying a consistent, structured approach to the solving of problems.
A general problem-solving approach and method can be defined, although variations will be required for specific problems.
Problems must be approached methodically, applying an algorithm, or step-by-step procedure by which one arrives at a solution.
1.1 Problem-Solving Process
The problem-solving process for a computational problem can be outlined as follows:
- Define the problem.
- Create a mathematical model.
- Develop a computational method for solving the problem.
- Implement the computational method.
- Test and assess the solution.
The boundaries between these steps can be blurred and for specific problems one or two of the steps may be more important than others. Nonetheless, having this approach and strategy in mind will help to focus our efforts as we solve problems
- Problem Definition:
The first steps in problem solving include:
- Recognize and define the problem precisely by exploring it thoroughly (may be the most difficult step).
- Determine what question is to be answered and what output or results are to be produced.
- Determine what theoretical and experimental knowledge can be applied.
- Determine what input information or data is available
Many academic problems that you will be asked to solve have this step completed by the instructor. For example, if your instructor ask you to solve a quadratic algebraic equation and provides you with all of the coefficients, the problem has been completely defined before it is given to you and little doubt remains about what the problem is.
If the problem is not well defined, considerable effort must be expended at the beginning in studying the problem, eliminating the things that are unimportant, and focusing on the root problem. Effort at this step pays great dividends by eliminating or reducing false trials, thereby shortening the time taken to complete later steps.
After defining the problem:
- Collect all data and information about the problem.
- Verify the accuracy of this data and information.
- Determine what information you must find: intermediate results or data may need to be found before the required answer or results can be found.
- Mathematical Model:
To create a mathematical model of the problem to be solved:
- Determine what fundamental principles are applicable.
- Draw sketches or block diagrams to better understand the problem.
- Define necessary variables and assign notation.
- Reduce the problem as originally stated into one expressed in purely mathematical terms.
- Apply mathematical expertise to extract the essentials from the underlying physical descrip- tion of the problem.
- Simplify the problem only enough to allow the required information and results to be obtained.
- Identify and justify the assumptions and constraints inherent in this model.
- Computational Method:
A computational method for solving the problem is to be developed, based on the mathematical model.
- Derive a set of equations that allow the calculation of the desired parameters and variables.
- The program should be executed on obtained or computed test data for which the answer or solution is either known or which can be obtained by independent means, such as hand or calculator computation.
- Intermediate values should be compared with expected results and estimated variations. When values deviate from expected results more than was estimated, the source of the devi- ation should be determined and the program modified as needed.
- A “reality check” should be performed on the solution to determine if it makes sense.
- The assumptions made in creating the mathematical model of the problem should be checked against the solution.
1.2 Problem Solving Example
As an example of the problem solving process, consider the following problem:
A small object is launched into flight from the ground at a speed of 50 miles/hour at 30 degrees above the horizontal over level ground. Determine the time of flight and the distance traveled when the ball returns to the ground.
- Problem Definition: As stated above, this problem is well defined. The following items could be considered in further defining the problem. - Additional information needed: - Properties of the object and the flight medium could affect the flight trajectory. For example, if the object is light in weight, has a relatively large surface area, and travels in air, the air resistance would affect its flight. If the air were moving (by wind, for example), the flight of the object would also be affected. If this information is not available, it will be necessary to assume that the medium has no affect on the trajectory of flight. - Acceleration of gravity also affects the flight. If no further information is available, it would be reasonable to assume that the gravitational acceleration at the surface of the Earth would apply. - The accuracy of the initial speed and angle of the object is needed to determine the necessary accuracy of the quantities to be computed. The problem is one for which we have some physical insight, as it could represent the throwing of a base- ball, although it is thrown from the ground instead of shoulder level. From this interpretation, the initial speed and angle seem reasonable. - Unit conversions needed: 1mile = 5280 feet 1hour = 60 minutes = 3600 seconds 360 degrees = 2π radians
- Output or results to be produced: It is clear from the problem statement that the results to be produced are the time of flight and the distance traveled. The units for these quantities haven’t been specified, but from our knowledge of throwing a baseball, computing time in seconds and distance in feet would be reasonable.
- Theoretical and experimental knowledge to be applied: The theory to be applied is that of ballistic motion in two dimensions.
- Input information or data: This includes the object initial velocity of 50 miles per hour at an angle 30 degree above horizontal.
- Mathematical Model:
To pose this problem in terms of a mathematical model, we first need to define the notation:
- Time: t (s), with t = 0 when the object is launched.
- Initial velocity magnitude: v = 50 miles/hour.
- Initial angle: θ = 30◦.
- Horizontal position of ball: x(t) (ft).
- Vertical position of ball: y(t) (ft).
- Acceleration of gravity: g = 32.2 ft/s^2 , directed in negative y direction. The key step in developing a mathematical model is to divide the trajectory into its horizontal and vertical components. The initial velocity can be divided in this way, as shown in Figure 1.1. From basic trigonometry, we know that
vh = v cos θ
vv = v sin θ
Figure 1.1: Initial velocity (v) divided into horizonal (vh) and vertical (vv) components.
Given the horizontal and vertical components of the initial velocity, the horizontal and vertical positions can be determined as functions of time. Since there is no external force acting to retard the horizontal motion, the object will move at a constant speed of vh in the horizontal direction
x(t) = vt cos θ
In the vertical direction, the object motion is retarded by gravity and its position is
y(t) = vt sin θ −
gt^2
- Words following percent signs (%) are comments to help in reading the Matlab state- ments.
- A word on the left of an equals sign is known as a variable name and it will be assigned to the value or values on the right of the equals sign. Commands having this form are known as assignment statements.
- If a Matlab command assigns or computes a value, it will display the value on the screen if the statement does not end with a semicolon (;). Thus, the values of v, g, and theta will not be displayed. The values of tg and xg will be computed and displayed, because the statements that computes these values does not end with a semicolon.
- The three dots (...) at the end of a line mean that the statement continues on the next line.
- More than one statement can be entered on the same line if the statements are separated by commas.
- The statement t = linspace(0,tg,256); creates a vector of length 256.
- The expression t.^2 squares each element in t, making another vector.
- In addition to the required results, the flight trajectory has also been computed and plotted. This will be used below in assessing the solution.
- The plot statement generates the plot of height against distance, complete with a title and labels on the x and y axes.
- Testing and Assessing the Solution:
This problem is sufficiently simple that the results can be computed by hand with the use of a calculator. There is no need to generate test data to check the results. One could even question the need to use the power of Matlab to solve this problem, since it is readily solved using a calculator. Of course, our objective here is to demonstrate the application of Matlab to a problem with which you are familiar. Executing the statements above provides the following displayed results:
time of flight (s): tg =
distance traveled (ft): xg =
Computing these quantities with a calculator can be shown to produce the same results. The flight trajectory plot that is generated is shown in Figure 1.2. This demonstrates another strength of Matlab, as it has taken care of the details of the plot generation, including axis scaling, label placement, etc. This result can be used to assess the solution. Our physical intuition tell us that this result appears to be correct, as we know that we could throw a baseball moderately hard and have it travel a distance of nearly 150 feet and that maximum height of about 20 feet also seems reasonable. The shape of the trajectory also fits our observations.
0 50 100 150 0
10
20
30
Distance (ft)
Height (ft)
Flight Trajectory
Figure 1.2: Matlab generated plot of flight trajectory
1.2.1 Programming Style
Programs that are not documented internally, while they may do what is request, can be difficult to understand when read a few months later, in order to correct or update them. Thus, it is extremely important to develop the art of writing programs that are well structured, with all of the logic clearly described. This is known as programming style. Elements of good programming style include:
- Use comments liberally, both at the beginning of a script, to describe briefly what it does and any special methods that may have been used, and also throughout the script to introduce different logical sections.
- Describe each variable briefly in a comment when it is initialized.
- Separate sections of code with blank lines.
- Indent multiple line structures to make them stand out as a logical unit.
- Use spaces in expressions to make them more readable (for example, on either side of operators and equal signs).
1.3 Computing Software
Before discussing Matlab in more detail, a brief discussion on computing software is useful.
Computer software contains the instructions or commands that the computer is to execute. Cate- gories include:
- System software
- Languages
- Tools
System Software
Computer system software provides:
- Language is closely tied to the hardware design.
- Machine specific: machine language for one computer is different from that of a computer having a different hardware design.
Assembly language:
- Also unique to a specific computer design.
- Commands or instructions are written in text statements instead of numbers.
- Assembly language programming requires good knowledge of the specific computer hardware. This is a tedious process, but it results in programs that are very fast, because they take advantage of the specific computer hardware.
- System software called an assembler translates the assembly language program to a machine language program for execution on the hardware.
High-level languages:
- Have English-like command syntax.
- Include languages such as Basic, Fortran, COBOL, Pascal, Ada, C, C++, and Java.
- Supported on many computer designs and knowledge of the specific hardware is not as critical in writing a program.
- System software called a compiler translates the program into machine language.
Compilation Process:
- Original program is called the source program
- Translated machine language program is called the object program.
- Errors detected by the compiler (called compile errors or syntax errors) must be corrected and compilation performed again.
- The process of compiling, correcting errors (or debugging) must often be repeated several times before the program compiles without compile errors.
Execution Process:
- To prepare the object program for execution, system software is applied to link other machine language statements to the object program and then load the program into memory.
- The program is executed and new errors, called execution errors, run-time errors or logic errors (also called bugs) may be identified.
- These program errors are caused when the programmer errs in determining the correct steps to be taken in the problem solution, such as an attempt to divide by zero.
- These errors must be corrected in the source program, which must again be compiled and link-loaded for execution.
- The process of program compilation, linking, and execution is shown in Figure 1.3.
Figure 1.3: High-level language program development
Even when a program executes without an error message, the results must be checked carefully to be sure that they are correct. The computer performs the steps precisely as specified in the source; if the wrong steps are specified, the computer will execute these wrong (but syntactically correct) steps and produce a result that is incorrect.
Matlab Mathematical Computation Tool
Matlab and other mathematical computation tools are computer programs that combine compu- tation and visualization power that make them particularly useful tools for engineers. Matlab is both a computer programming language and a software environment for using that language effectively.
The name Matlab stands for Matrix laboratory, because the system was designed to make matrix computations particularly easy. Don’t worry if don’t know what a matrix is, as this will be explained later. The Matlab environment allows the user to manage variables, import and export data, perform calculations, generate plots, and develop and manage files for use with Matlab.
The Matlab environment is an interactive environment:
- Single-line commands can be entered and executed, the results displayed and observed, and then a second command can be executed that interacts with results from the first command that remain in memory. This means that you can type commands at the Matlab prompt and get answers immediately, which is very useful for simple problems.
- Matlab is a executable program, developed in a high-level language, which interprets user commands.
- Portions of the Matlab program execute in response to the user input, results are displayed, and the program waits for additional user input.
Echo: To display commands or other input typed by the user.
Print: To output information on a computer printer (often confused with “display” in the text- book).
Section 2
Matlab Technical Computing
Environment
Matlab provides a technical computing environment designed to support the implementation of computational tasks.
Briefly, Matlab is an interactive computing environment that enables numerical com- putation and data visualization.
Matlab has hundreds of built-in functions and can be used to solve problems ranging from the very simple to the sophisticated and complex. Whether you want to do some simple numerical or statistical calculations, some complex statistics, solve simultaneous equations, make a graph, or run and entire simulation program, Matlab can be an effective tool.
Matlab has proven to be extraordinarily versatile and capable in its ability to help solve problems in applied math, physics, chemistry, engineering, finance – almost any application area that deals with complex numerical calculations.
2.1 Workspace, Windows, and Help
Running Matlab
- Unix: From a terminal window, type matlab, followed by the Enter key
- Win95: double-click on the Matlab icon or select Matlab from Start/Programs
Display Windows
- Command window Enter commands and data, display results Prompt >> or EDU>>
- Mathematical construct that has a value or set of values.
- Constructed from numbers, operators, and variables.
- Value of an expression found by typing the expression and pressing Enter
2.2.1 Numbers
Matlab represents numbers in two form, fixed point and floating point.
Fixed point: Decimal form, with an optional decimal point. For example:
Floating point: Scientific notation, representing m × 10 e
For example: 2. 6349 × 105 is represented as 2.6349e
It is called floating point because the decimal point is allowed to move. The number has two parts:
- mantissa m: fixed point number (signed or unsigned), with an optional decimal point (2. in the example above)
- exponent e: an integer exponent (signed or unsigned) ( 5 in the example).
- Mantissa and exponent must be separated by the letter e (or E).
Scientific notation is used when the numbers are very small or very large. For example, it is easier to represent 0.000000001 as 1e-9.
2.2.2 Operators
The evaluation of expressions is achieved with arithmetic operators, shown in the table below. Operators operate on operands (a and b in the table).
Operation Algebraic form Matlab Example Addition a + b a + b 5 + Subtraction a − b a - b 23- Multiplication a × b a * b 3.14*0. Right division a ÷ b a / b 56/ Left division b ÷ a a \ b 8
Exponentiation ab^ a ^ b 5 ^
Examples of expressions constructed from numbers and operators, processed by Matlab:
ans = 7
3 - 3 ans = 0 4/ ans =
Prompt >> is supplied by Matlab, indicates beginning of the command.
ans = following the completion of the command with the Enter key marks the beginning of the answer.
Operations may be chained together. For example:
ans = 10
422 + 648 + 2* ans = 540 4 * 4 * 4 ans = 64
Instead of repeating the multiplication, the Matlab exponentiation or power operator can be used to write the last expression above as
>> 4^
ans = 64
Left division may seem strange: divide the right operand by the left operand. For scalar operands the expressions 56/8 and 8\56 produce the same numerical result.
ans = 7
8
ans = 7
We will later learn that matrix left division has an entirely different meaning.
Syntax