Presentation is loading. Please wait.

Presentation is loading. Please wait.

Engineering 1181 Final Exam Review

Similar presentations


Presentation on theme: "Engineering 1181 Final Exam Review"— Presentation transcript:

1 Engineering 1181 Final Exam Review

2 What to bring with you? Pen / pencil and eraser. P. 2

3 Overview Final exam is cumulative, including Class lectures
Team working Problem solving method Excel (graphing, cell referencing, data collection and analysis) Matlab lectures (next page) Lab 2 – Lab 8 (go over all the lab assignments and lab procedures)

4 Overview MATLAB Use of input/output statements
Use of built in functions Array operations (dot operators) Array Accessing Display using fprintf Graphing, following good graphing practices Use of loops with arrays Array indexing Use of conditional statements User-defined functions Tic and toc application

5 MAT - Structured Problem Solving
Define Represent Plan Implement 5.Evaluate PROBLEM SOLVING: So we just saw this the other day, our PROBLEM SOLVING METHOD and its five steps. Define the problem as well as possible Represent it in a fashion that helps you understand it Put together a plan for how to solve it Implement the plan Evaluate how your implementation of the plan worked out. Rev: , PAC MAT - Structured Problem Solving

6 Structured Problem Solving
flowcharts develop not document high level executable only coding guideline specifics not included Symbols algorithm top down step-wise pseudo code flowchart higher level verification STRUCTURED PROBLEM SOLVING: In addition to using pseudo code along with the TOP DOWN STEP-WISE refinement approach to planning your program, FLOWCHARTS are another tool that can be used as part of the code planning/development process. FLOWCHARTS are primarily a development tool. They are not a documentation tool to be used after the code has been developed and programmed. While the TOP DOWN STEP-WISE refinement technique ultimately gets us a very detailed solution to a program, FLOWCHARTS give us a much higher level view. Only executable portions of your code should be included in a FLOWCHART and, in fact, the FLOWCHART should concentrate on where decisions are made, where looping occurs, where input and output occur. General processing is normally just represented as a single block in the FLOWCHART. For example, if you had several or twenty or one-hundred equations that need to be calculated as part of your program, these would be represented just as a single block, rather than, say, having a processing block for each equation. You can get the details of your algorithm by using a TOP DOWN STEP-WISE refinement technique and combining it with pseudo code. Following that kind of development/planning process should lead fairly directly to an complete outline of your program which should then be straightforward to implement. If you combine the algorithm that you develop with a FLOWCHART, it will help provide you with an overall view of the flow that your program will take. It can make it easier to determine if the pseudo code modules that you have developed fit together as you planned and act as a verification tool when developing your program. While FLOWCHARTS may seem like overkill for relatively small and basic programs, they can be incredibly useful, and in fact necessary, in order to manage significantly more complex software. Being comfortable with the basics and having some practice at using FLOWCHARTS when developing code can be very useful when you write larger and more complex software. FLOWCHARTS are a coding guideline that give a high level view of your program and are not expected to contain a lot of specifics. Again, they are to emphasize overall flow and major actions/decisions, as well as input to/output from your program. There are specific symbols that are used to represent actions like processing, input from the keyboard, output to a monitor, input from and output to data files, looping, branching, starting, and stopping. Some of these symbols are show in the FLOWCHART to the right. A FLOWCHART symbol cheat sheet has been provided with the assignment and/or reading material. Additionally, suggestions for resources that access these symbols are provided at the end of the presentation.

7 Script files MATLAB allows you to save any series of commands in a file and will execute the commands sequentially as if they were typed directly into the command window. MATLAB program text file sequence start to finish executable commands non-executable comments – (%)

8 RULES ABOUT VARIABLES NAMES
Can be up to 63 characters long. Must begin with a letter. Can contain letters, digits, and the underscore character (no spaces). MATLAB is case sensitive; it distinguishes between UPPERCASE and lowercase letters. Modified 01/28/11 by R.C.Busick, HI 221 , Instructor notes: Matlab is case sensitive. Matlab distinguishes between upper and lower case. So, even if the only difference between two variable names is the case of one (or more letters), then the variables are completely separate variables. Avoid naming variables names that are used by MATLAB for example, sum, exp, sin, cos, sqrt, length, mean, max, min etc.

9 SAVING A SCRIPT FILE Once the script file is completed, it must be saved. In our class use Save As to your desktop or USB drive. This should be the same as the working directory you specified when you started MATLAB. The name of the script file follows some rules Valid File Names Invalid File Names Prob1a.m Prob 1a.m (Note a blank) Prob_1a.m aProb.m (Cannot start with numeric) Prob-1a.m (No special characters) Modified 01/26/11 by R.C.Busick, HI 221 , Instructor notes: The file should be saved to a floppy/zip disk or possibly the Temp/Tmp directories. Remind students that if they use the Temp/Tmp directories, they copy the file to their own floppy/zip disks before leaving. Work can also be saved on their N: drive.

10 Input Command Window (CW) CW and script file share memory input()
assigns value to single variable prompts user numeric character prompt flag – ‘s’ response quotes INPUT: Two primary methods to be discussed and/or used. The first will be getting values into a program via the Command Window and the second will be via the input() function. Once students have a little experience, most input will come via the input() function.

11 Output Omit semicolon (;) disp() like omitting semicolon without name
variables and values (numeric, text, variables must have a value) fprintf() most flexible/powerful option write to monitor or file fprintf(FID, FORMAT, V1, V2, ...) FID – file ID, 1 for monitor/Command Window FORMAT – controls appearance V1, V2, ... – values and variables being written INPUT: Two primary methods to be discussed and/or used. The first will be getting values into a program via the Command Window and the second will be via the input() function. Once students have a little experience, most input will come via the input() function.

12 Repetition Indefinite: while start test – (number < 10) contents
total = 0; number = 0; while (number < 10) number=number+1; total=total+number; end Indefinite: while start test – (number < 10) contents end total = 0; number = 1; while (number <= 10) total=total+number; number=number+1; end OUTLINE: WHY? Why we use repetition structures in programming? What is our motivation behind them? WHAT? What are repetition structures made of? That is, what are the common elements that all repetition structures have. INDEFINITE (WHILE) First we’ll look at the indefinite loop aka the WHILE loop. An indefinite loop is one for which we do not know in advance how many times the loop will execute. DEFINITE (FOR) Second, we’ll look at the definite loop aka the FOR loop. A definite loop is one for which the number of times through the loop or iterations is known in advance. In addition to looking at the basics of for loops, we’ll also look at how they go hand in hand with vectors and matrices and for matrices we’ll see how we use a technique called ‘nesting’ which requires us to put a loop inside of a loop. REMINDERS Finally, we’ll wrap things up with a few special cases and odds and ends which we’ll mention now to get students thinking about things, but will be more clear when we’ve covered SELECTION STRUCTURES a little bit later.

13 Repetition Definite: for start counter test – (TRUE/FALSE?) contents
… for c = start : step : stop end Definite: for start counter test – (TRUE/FALSE?) <= stop? OR >= stop? contents end total = 0; number = 1:1:10; for i=1:length(number) total=total+number(i); end total DEFINITE: FOR Now let's look at a DEFINITE loop aka a FOR loop. As the name indicates, FOR loops execute a known number or DEFINITE number of times. FOR loops have the same basic elements that WHILE loops have with a couple added features. As with WHILE loops, FOR loops have a START, a TEST that evaluates to TRUE or FALSE, CONTENTS which are all of the statements that will be repeated each time the loop executes, and an END which indicates where the repeated statements end. FOR loops also have a couple differences from WHILE loops. The first is that FOR loops have a COUNTER variable. The COUNTER variable steps through a series of values beginning with the value given by START. Each time through the loop, COUNTER will be changed by the amount of STEP. The loop will stop when the TEST no longer evaluates to TRUE. Where the TEST for a WHILE loop has effectively an infinite number of combinations, the TEST for a FOR loop is more restricted. Despite being much more restricted than the WHILE loop TEST, students should be told that the STEP for a FOR loop can be either positive or negative and does not have to be an integer, although loops are commonly used that way. So, if the STEP is positive, the TEST evaluates to TRUE when the COUNTER value is <= to the STOP and if the STEP is negative, the TEST evaluates to TRUE when the COUNTER is >= to the STOP.

14 Graphing Basics help plot is your friend
plot(x_data, y_data) equal length vectors plot(x_data, y_data, 'control string') color, data point, line style xlabel('Label for x-axis') ylabel('Label for y-axis') title('Title of my plot') axis([xmin, xmax, ymin, ymax]) BASICS: First, 'help plot' is your friend. help in general is your friend, but particularly for plotting because it gives the quick and dirty version of how plotting works along with many of the necessary flag settings and points you in the direction of the other functions (xlabel, ylabel, title, etc.) that are associated with plotting. It also provides a quick reference of how to generate different line styles. Can't emphasize enough just how much 'help plot' is everyone's friend. The basic approach when using the plot() function is plot(x_data, y_data) where the number of elements in the x_data set and the y_data set must be the same. MATLAB gets cranky when it wants to use two vectors together and they don't turn out to be the same size. It's possible to use plot() with just plot(y_data) and eliminate the x_data set, although this approach is not as commonly used. When plot() is used with only the y_data set, then the index of each element (1, 2, 3, ...) in the y_data set is plotted on the x-axis. If you want to control the data marker, line style, color of the plot, then you can easily do that by adding a third argument to the function call to plot() in the form of a control string. The control string is optional and the order of the elements in the control string is unimportant. Again, 'help plot' will tell you many of the things you'll want to know to learn how to put together useful control strings. There are additional instructions in the Gilat text in Chapter 5 that provide even more control over line thickness and other properties. 'help plot' will get you at least 95% of what you normally will need to know. As with all things MATLAB, it's easy to experiment with the plot() function directly from the Command Window. It's a very good way to get experience...make it so. Rev: , PAC MAT - Graphing

15 Multiple Plots Per Graph
multiple calls to plot() hold on after first plot() hold off after final plot() single call to plot() help legend is also your friend plot(x1,y1,x2,y2) plot(x1,y1,'control1',x2,y2,’control2’) legend('set1','set2') EXTRAS – MULTIPLE PLOTS PER GRAPH 1 Often we want to put multiple plots on a single graph. MATLAB gives us a couple ways of doing this. The first is to include multiple (x,y) pairs of data sets as arguments to plot(). Using the example in the slide x1 and y1 need to have the same number of elements and x2 and y2 need to have the same number of elements, but the number of elements in the x1/y1 pair doesn't need to be the same as the number in the x2/y2 pair. The control1 and control strings again represent manual control over the data point, line style, coloring, etc. that you can exert over MATLAB if you wish. The order is x_data, y_data, 'control string'. Using plot() in this fashion to put multiple plots on the same graph will work when you know in advance how many plots you want on the graph. If you don't know, you'll need to use the plot(), hold on, plot(), plot(), ..., hold off sequence that will be shown next. Regardless of how you get multiple plots on a single graph, you will want to establish a legend to indicate which plot is which. Again, you want to put a legend on the graph, no big surprise that the function to do so is called legend(). legend() accepts a sequence of control strings with words of your choosing that will be matched up with the plots. It's important to realize that MATLAB doesn't have any special smarts when it comes to legend(). You the programmer need to ensure that the order of the sequence of control strings that is being provided to legend() is the same as the order of the data sets that are being plotted. MATLAB isn't matching words up with data sets. It's just going to display in the order you provide, so make sure the orders match up. Again...can't say it enough, help legend is your friend. plot(x1,y1,'control1') hold on plot(x2,y2,'control2') plot(x3,y3,'control3‘) hold off legend('set1','set2','set3')

16 Decisions TRUE simple FALSE complex branching a = 4; non-zero b = 12;
evaluate to one FALSE zero branching a = 4; b = 12; simple (a < 5) complex (a < 5) & (b > 20) DECISIONS: Without the programming structures that we're covering in this presentation our software would not have any ability to make decisions. Without that ability we could only write software that would always do the same thing. It would never "branch" and follow a "different" path. The ability to make decisions is what gives our software "intelligence", not that this is really has intelligence, but it might be one way of considering the decision making process that software is capable of. This ability to make decisions allows software to take path B instead of path A from time to time. Or as we've seen with loops to decide how many times to perform a loop or when to stop based on some condition. The key thing about decision making structures is that it all boils down to TRUE or FALSE. The conditions that we're required to set up may be simple or they may be complex, but in the end they will all eventually evaluate to either TRUE or FALSE. Looking at the example in RED we can ask some questions. Is a TRUE or FALSE? It's TRUE because it's non-zero. Again, same with b, TRUE or FALSE. Also, TRUE...also non-zero. What about the relationship a<5? Given a=4, this evaluates to? One. So the relationship is TRUE. What about the second example, which is a little more complex. Naturally a<5 evaluates to one. Where to next? Next we evaluate b>20, which is FALSE which evaluates to zero. Now we have 1 & 0, which evaluates to zero, which is FALSE. There is a precedence of operators. It's listed in Gilat. Students should understand the precedence and look at the table.

17 Relational Operators < less than > greater than <= less than or equal to >= greater than or equal to == equal to ~= not equal to A < B A > B A <= B A >= B A == B A ~= B RELATIONAL OPERATORS: For the most part these are self-explanatory. Everyone should have seen something semi-equivalent to the first four. The last two, maybe not. In programming "==" is a comparison "=" is an assignment. This is a little different than it is mathematically. The not equal to relational operator takes a little getting used to just because the "~" (tilde) doesn't get used to often. Key thing here is the reminder that "=" is an assignment and "==" is a comparison.

18 Logical Operators – AND
& two operands A & B TRUE if both operands are TRUE FALSE if either operand is FALSE salsa = 1; guacamole = 0; salsa & guacamole fish = -5; chips = 1; fish & chips LOGICAL OPERATORS - AND The ampersand or "and sign" is the AND operator. It takes two operands and evaluates to TRUE if both operands are TRUE and evaluates to FALSE if EITHER operand is FALSE. Probably obvious that salsa is TRUE and guacamole is FALSE. Following the rules salsa & guacamole evaluates to zero or FALSE. Slightly more complicated. Is fish TRUE or FALSE? This might be a good question to ask since people often associate negative values with FALSE. However, fish is non-zero, so in MATLAB's eyes it is TRUE. Therefore fish & chips evaluates to one, which is TRUE.

19 Logical Operators – OR | two operands A | B
TRUE if either operand is TRUE FALSE if both operands are FALSE eggs = 1; bacon = 0; eggs | bacon toast = -5; muffin = 1 toast | muffin LOGICAL OPERATORS – OR: The vertical bar thingy (that's the technical name for it, by the way) is the OR operator. Sometimes people have a hard time finding it on the keyboard. It's usually directly beneath the <BACKSPACE> key and directly above the <ENTER> key. You have to shift to activate it. The OR operator requires two operands and evaluates to TRUE if either operand is TRUE and evaluates to FALSE only when both operands are FALSE. In the first example, eggs is set to one, so it's TRUE. bacon is set to 0, so it's false. eggs OR bacon evaluates to TRUE because at least one of them is TRUE> In the second example, toast is set to -5, so it's TRUE. Again, this might be a good place to ask if toast is TRUE or FALSE since people have a tendency to associate FALSE with zero and negative numbers. muffin is set to 1, so it's TRUE. So, toast OR muffin is TRUE and would evaluate to one.

20 Logical Operators – NOT
~ one operand ~A negates operand TRUE if operand FALSE FALSE if operand TRUE potato = 7; ~potato tomato = 0; ~tomato LOGICAL OPERATORS – NOT: The NOT operator is the "~" or tilde (til-duh). It takes a single operand and negates the sense of that operand. If the operand is TRUE, then with the ~ in front the result is FALSE. If the operand is FALSE, then with the ~ in front, the result is TRUE. Is potato TRUE or FALSE? It's non-zero, so it is TRUE. Therefore, ~potato is FALSE, or zero. Is tomato TRUE or FALSE? It's zero, so it is FALSE. Therefore, ~tomato is TRUE, or one.

21 Math, Relational and Logical Operators Order of Precedence
Name Highest 1 ( ) Parentheses 2 ^ Exponent 3 ~ Negation (Logical "NOT") 4 * / Multiply, Divide 5 + – Add, Subtract 6 < > <= >= == ~= Relational Operators 7 & Logical "AND" Lowest 8 | Logical "OR" MATLAB - 8

22 Selection Structures if-elseif-else-end multiple comparison types
relational operators logical operators SELECTION STRUCTURES: Here's where the real decision making abilities of the language come in. We have two selection structures that allow us to make decisions. The if-elseif-else-end structure and the switch-case structure. if-elseif-else-end is a robust selection structure. It’s capable of simple as well as very complex comparisons using all of the logical and relational operators. It’s the only one we need. switch-case is a simplified version of if-elseif-else-end. it can only do “==“ comparisons.

23 Matrix Addressing Just as with vectors, individual elements of matrices can be accessed. The elements of a matrix are addressed by their row number and column number. For example let us define a 2 x 4 matrix “mat” as follows: >> mat = [ ; ] mat = Instructor notes: This is an important concept about matrix addressing. Matrix_name(a,b) addresses the element in a row and b column 1st Row, 2nd Column 2nd Row, 3rd Column >> mat(2,3) ans = 8 >> mat(1,2) ans = 3

24 Matrix Addressing : Examples
>> B = A(1:3, 2:4) B = The sub matrix is assigned to a matrix B >> A = [ ; ; ; ] A = Instructor notes: Here we have some examples of using the colon operator in accessing elements in a matrix.

25 Matrix Addressing : Examples
ans = % All Columns >> A = [ ; ; ; ] A = >> A( : , 2:4) ans = % All rows Instructor notes: Here we have some examples of using the colon operator in accessing elements in a matrix.

26 Using a colon (:) when addressing matrices
Elements in all the rows of column 3 Elements in all the columns of row 2 Elements in columns 2 through 5 in all the rows Elements in rows 2 through 4 in all the columns Elements in rows 1 through 3 and in columns 2 through 4 Instructor notes: The colon operator works for matrices much like it does for vectors but with more combinations for which it can be applied. The colon operator being used with a matrix can appear twice within the parentheses. It can be used to specify the range of the rows and/or the range of the columns that are being accessed. The sequence is: array_name( row_range , column_range ) If, for either the row or column range, only a colon is provided then all of the rows or columns will be accessed. A single row/column can be accessed by eliminating the colon and referring only to the specific row in the subscripting. A second way to access a single row/column is to set the beginning row/column and ending row/column to the same value. For example A(2:2, :) is the same thing as A(2, :) Again, if you specify rows/columns outside of the range of the matrix, Matlab will give you an error message. Also, like vectors, if you provide a beginning/ending range with the colon operator you must provide a beginning AND ending range. For example A(2:, 3:5) is NOT acceptable.

27 Scalar-vector math summary (or scalar-matrix case)
For a scalar c and a vector v: (can be also applied to scalar- matrix case) Addition v + c or c + v Subtraction v – c or c – v Multiplication v * c or c * v or v .* c or c .* v Division v / c or c ./ v or v ./ c Exponent v .^ c or c .^ v When in doubt, you can always use a dot operator for Multiplication, Division, or Exponent

28 Vector-vector math summary (or matrix-matrix case)
For two vectors x and y: (can be also applied to matrix- matrix case) Addition x + y or y + x Subtraction x – y or y – x Multiplication x .* y or y .* x Division x ./ y or y ./ x Exponent x .^ y or y .^ x You must always use the dot operator for Multiplication, Division, and Exponent

29 Example Calculate y = (4a2 + a) / (2+a) for a = 1, 2, 3 and 4
Define a = [ ] >> a = [ ] ; a = >> y = ((4 * a .^ 2) + a) ./ (2 + a) y = MATLAB - 3

30 Built-in vector functions
MATLAB has built-in functions for vectors When v is a vector: max(v) Returns the largest element in v min(v) Returns the smallest element in v mean(v) Returns the average value of the elements in v sum(v) Returns the sum of the elements of v length(v) Returns the number of elements in v sort(v) Sorts the elements of v Instructor notes: This slide lists some basic and useful array functions that Matlab has built in. This might be a good time to re-emphasize the fact that these are built in functions and the names of most of them might commonly be picked as variable names and that this should not be done (even though it is legal) because it will render the built in function useless until the variable has been cleared from memory. The descriptions for each of these functions are straightforward and indicate what will happen when A is a vector. Additionally, all of these functions work with matrices, too, but how the function works, is slightly different. Other useful functions can be found on pages 64-65 MATLAB - 3

31 Characteristics of Flow Charts
Useful tool in program development Describes the logic flow of the program Not a complete description of program Not only tool to use Made before writing the program No formal standards, but common guidelines Instructor notes: Flow charts are a graphical representation of an algorithm and are well suited for programmers which can visualize the flow of their programs well. It can be used as an aid to writing the actual program, and there are no formal standards, but some common guidelines exist, which will be discussed in the remainder of this lecture Flow charts can be a useful tool in program development. They do not typically show a complete description of the program, and are typically used in conjunction with other tools. Flow charts should be made before writing the program, but can also be developed by programmers trying to understand another programmer’s code after it has been written. The final program may differ from the flowchart as only executable statements are shown in the flowchart. Specific equations and tests are also not included. When using flow charts typically every main and sub-program is charted.

32 Flow Chart Symbols Decision or Selection Structure: General
Processing: Start or End a Program: Quit? Y N Start process Instructor notes: The beginning and end of a program are normally shown within a rectangle with rounded corners. You may use any common text such as “start”, “begin”, or in the case of a subprogram, “enter” for example. The arrow designates the flow of the program. Normally the arrow will point to the next sequential program block in the flow chart. The top-down example uses if-then statements. These are represented by selection structure. A question is posed inside the block, and depending on if the result is true or false, or yes or no, the program may follow a different arrow and execute different code. General commands may be placed in a rectangle. This commands could be completing some mathematical equation for example. End A<B? F T

33 SAMPLE FLOWCHART

34 Creating a function file
The first line in the function file should be the function definition line: function [output vars] = function_name(input vars) Instructor Notes: MATLAB 2009 has created a template for function files. But to avoid any confusion, students should open the regular script file as blank m file and then use the function word in the beginning to specify it as function file. If this is omitted, MATLAB interprets the file as a script file, not a function file. MATLAB - 7

35 Saving Function Files After adding commands, save the function file using the name function_name.m Thus, if the name of your function is my_calc, save the function file as my_calc.m function [output vars] = function_name(input vars)

36 What to bring with you? Pen / pencil and eraser. P. 36


Download ppt "Engineering 1181 Final Exam Review"

Similar presentations


Ads by Google