Bruce Mayer, PE Registered Electrical & Mechanical Engineer BMayer@ChabotCollege - PowerPoint PPT Presentation

slide1 n.
Skip this Video
Loading SlideShow in 5 Seconds..
Bruce Mayer, PE Registered Electrical & Mechanical Engineer BMayer@ChabotCollege PowerPoint Presentation
Download Presentation
Bruce Mayer, PE Registered Electrical & Mechanical Engineer BMayer@ChabotCollege

play fullscreen
1 / 45
Download Presentation
Bruce Mayer, PE Registered Electrical & Mechanical Engineer BMayer@ChabotCollege
Download Presentation

Bruce Mayer, PE Registered Electrical & Mechanical Engineer BMayer@ChabotCollege

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Engr/Math/Physics 25 Chp4 MATLABProgramming-1 Bruce Mayer, PE Registered Electrical & Mechanical

  2. Learning Goals • Write MATLAB Programs That can MAKE “Logical” Decisions that Affect Program Output • Write Programs that Employ LOOPing Processes • For→ No. Loops know a priori • while → Loop Terminates based on Logic Criteria • Use the MATLAB DeBugger to Correct Errors (time permitting)

  3. What’s an “Algorithm” • A postage stamp issued by the USSR in 1983 to commemorate the 1200th anniversary of Muhammad al-Khowarizmi, after whom algorithms are named.

  4. ALGORITHM  an ORDERED SEQUENCE of PRECISELY defined instructions that performs some task in a finite amount of time. ORDERED means that the instructions can be NUMBERED, but an algorithm must have the ability to ALTER the order of its instructions using a CONTROL structure. There are three categories of algorithmic operations → Next Slide: Algorithm Defined

  5. SEQUENTIAL OPERATIONS → Instructions executed in order CONDITIONAL OPERATIONS → Control structures that first ask a question to be answered with a true/false response and then select the next instruction based on the answer ITERATIVE OPERATIONS (LOOPS): Control structures that repeat the execution of a block of instructions Algorithmic Operations

  6. STRUCTURED PROGRAMMING  A technique for organizing and coding computer programs in which a hierarchy of modules is used, each having a single entry and a single exit point, and in which control is passed downward through the structure withOUT UNconditional branches to higher levels of the structure. Three types of control flow are used: (1) sequential, (2) test, and (3) iteration. Structured Programming GoTo statements

  7. Structured programs are easier to write because the programmer can study the overall problem first and then deal with the details later. Modules (functions) written for one application can be used for other applications (this is called reusable code). Structured programs are easier to debug because each module is designed to performjust one task and thus it can be tested separately from the other modules. Structured Program Advantages

  8. Structured programming is effective in a teamwork environment because several people can work on a common program, each person developing one or more modules. Structured programs are easier to understand and modify, especially if meaningful names are chosen for the modules and if the documentation clearly identifies the module’s task. Structured Program Advantages

  9. State the problem concisely Use Math Eqns/Relns Whenever possible Specify the data to be used by the program. This is the “input.” In physical Problems These are typically Boundary Conditions Initial Conditions Constraints Parameters Specify the information to be generated by the program. This is the “output.” Developing Computer Solns

  10. Work through the solution steps by hand or with a calculator; Use a simpler set of data if necessary Test for EXTREME cases withInput or Output = ±∞, 0, ±1 Write and Run the program Correct Compile/Execution Time Errors Missing Comma or Parens, MisTypedVar names, etc. Correct RunTime Errors e.g.,NaN’s, inf’s, Divide-by-Zero, Complex Numbers, etc. Developing Computer Solns cont

  11. Check the output of the program with your hand solution(s) Run the program with your input data and perform a reality check on the output. Output MUST NOT Violate the Laws of Physics; e.g., in Statics (ENGR36) a CABLE canNOT support NEGATIVE Tension (you can’t PUSH something with a ROPE) Objects canNOT have NEGATIVE Weight or Mass (at least not until we figure out AntiGravity methods) In ENGR43 Physical Resistors, Capacitors, and Inductors can NOT have NEGATIVE Values Developing Computer Solns cont

  12. If you will use the program as a general tool in the future, test it by running it for a range of reasonable data values; Perform a Reality Check on the results Developing Computer Solns cont

  13. Proper selection of variable names to reflect the quantities they represent Use DESCRIPTIVE and/or LONG names Use of comments within the program Also helps CLARIFY the WRITING of the Code Use of structure charts Like an ORG Chart for your Software Program Structure charts show how variables pass between modules in a computer program. Effective Documentation

  14. Anatomy of a Structure Chart Module the called module

  15. Write a program to find the UNIT price for a given pizza. The size of the pizza will be provided in inches. The result must be cost/inch2 Example: Pizza Pricing Problem

  16. Use of flowcharts Each flowchart has one starting point and one or more ending points that are drawn with a rounded rectangle or oval. Steps, actions, or tasks are drawn with rectangles. It helps to use verbs in describing the steps. Decisions are drawn with diamonds with labels at the exits. The arrows show the order the steps are taken. The shapes in the flowchart are often numbered to make it easier to refer to them Drawing a flowchart of a software component makes the flow of control easier to understand Effective Documentation cont

  17. FlowCharting Example • Basic House Painting • Note the Cascade of Decision-Diamonds

  18. A verbal description of the program, often in pseudocode. Generic way of describing an algorithm, without use of any specificprogramming language Helps programmers to PLAN an algorithm Not an actual programming Language, but may borrow syntax from popular programming languages Styles vary Effective Documentation cont

  19. Example Problem: Calculate the bill when someone buys a specific no. of some item: PseudoCode: PROMPT for number of items being purchased READ number of items being purchased PROMPT for price per item READ price per item CALCULATE subtotal CALCULATE tax CALCULATE total DISPLAY total PseudoCode Example

  20. To Describe input, output, computations, etc., the following terms are often used: Input: INPUT, READ, GET Output: PRINT, DISPLAY, SHOW Compute: COMPUTE, CALCULATE, DETERMINE Initialize: SET, INIT Add one: INCREMENT, BUMP, STEP Decisions: TEST, IF/THEN/ELSE, WHILE/DO PsuedoCode: Common Terms

  21. Ensure that the the task is completely specified Issues to Consider What data is known before the program runs? What data must be input by the user? What computations will be performed on the data? What data will be output(displayed) to the user? PsuedoCode Algorithms

  22. Solve QuadraticEquation • PsuedoCode • Get coeffs a, b, & c • Let d = b2 − 4ac • If d < 0 print 'no real solutions' and go to step 5 • Let X1 = (−b + SQRT(d))/(2a) • Let X2 = (−b − SQRT(d))/(2a) • Print X1 and X2 • Stop

  23. Real World Problem: Calculate the allowance for two children, based upon 75¢ per year-of-age Known Values Pay Rate = 75 ¢/year Inputs Child Age Calculations Allowance = Age x Rate Outputs Allowances for each child PsuedoCode Example

  24. Careful PseudoCode Algorithm: PROMPT for Age of Child1 READ Age of Child1 PROMPT for Age of Child2 READ Age of Child2 CALCULATE Allowance for Child1 = [Age of Child1] x Rate CALCULATE Allowance for Child2 = [Age of Child2] x Rate DISPLAY Allowance for Child1 DISPLAY Allowance for Child2 PsuedoCode Example cont

  25. Flowchart  a graphical representation of algorithms Program Design - FlowChart • Rectangle is used for calculations • Parallelogram is used for input and output • Circle is used as connector • Diamond is used as decision • Symbols are connected by arrows to represent the order of the operations;i.e., the direction of program flow

  26. Calculations (e.g. arithmetic expressions) are shown in rectangles Example: Total = Cost + Tax Total = Cost + Tax Num = Num + 1 FlowChart Symbols – Calc’s • ExampleNum = Num + 1 • add one to the current value of Num and make that the new value of Num

  27. Data input and output are shown in parallelograms READ Num WRITE Num FlowChart Symbols – In/Out Put • Input  a read operation of data from a peripheral device to memory • e.g., a user typing in data at a keyboard • Output a write operation of data to a peripheral device from memory • e.g., data displayed to the monitor

  28. Decisions are shown within Diamonds and specify a condition to be tested False Gross > 50000 Rate = 0.28 True Rate = 0.31 FlowChart Symbols – Decisions • Based on the condition being TRUE or FALSE, the next operation will be determined • A decision is composed of : • A condition • An operation to be done if condition is TRUE • Possibly an operation to be done if condition is FALSE

  29. Every algorithm starts somewhere and terminates somewhere start input num square = num x num print square stop FlowChart Symbols – Start/End • Every flowchart must have one start symbol and one end symbol • Start and Stop symbols are ovals • A start symbol denotes the start of the algorithm • An end symbol indicates the algorithm has terminated

  30. Sequential-FlowChart for the Previous Pseudocode Algorithm: start prompt Age1 input Age1 prompt Age2 input Age2 Allow1 = Age1 x Rate Allow2 = Age2 x Rate Print Allow1 Print Allow2 stop FlowChart Example • PROMPT Age of Child1 • READ for Age of Child1 • PROMPT Age of Child2 • READ for Age of Child2 • CALCULATE • Allowance for Child1 = Age of Child1 x Rate • CALCULATE • Allowance for Child2 = Age of Child2 x Rate • DISPLAY Allowance for Child1 • DISPLAY Allowance for Child2

  31. Common Flowchart Symbols Terminator. Shows the starting and ending points of the program. A terminator has flowlines in only one direction, either in (a stop node) or out (a start node). Data Input or Output. Allows the user to inputdata and results to be displayed. Processing. Indicates an operation performed by the computer, such as a variable assignment or mathematical operation. Decision. The diamond indicates a decision structure. A diamond always has two flowlines out. One flowlineout is labeled the “yes” branch and the other is labeled the “no” branch. Predefined Process. One statement denotes a group of previously defined statements. For instance, “Calculate m!” indicates that the program executes the necessary commands to compute m factorial. Connector. Connectors avoid crossing flowlines, making the flowchart easier to read. Connectors indicate where flowlines are connected. Connectors come in pairs, one with a flowline in and the other with a flowline out. Off-page connector. Even fairly small programs can have flowcharts that extend several pages. The off-page connector indicates the continuation of the flowchart on another page. Just like connectors, off-page connectors come in pairs. Flowline. Flowlines connect the flowchart symbols and show the sequence of operations during the program execution. Common FlowChart Symbols

  32. Top-Down Dsgn: Structure Chrt • As we Have Seen a FlowChart: • Details exactly HOW a program will do each task • In contrast, the next design tool, the Structure Chart: • Shows only WHAT tasks your program will do (not HOW it will complete them)

  33. Structure Chart • Structure charts are Hierarchical diagrams → A form of an “Org Chart” • They diagram the OverAll program (organization) Structure • They show the Relationship between all the Tasks (workers) in the program • They indicate which Data (Information) is shared by the tasks (workers)

  34. A large program design is first broken into tasks Tasks are repeatedly dividedinto even smaller subtasks Rectangles are used to represent tasks/subtasks within the program Lines are used to hierarchically connect the tasks/subtasks Subtasks are diagrammed below the task that they are part of Task SubTask1 SubTask2 Creating Structure Charts

  35. Passing of data between tasks is shown by arrows going up from or downto the task’s rectangle Task Data1 Data1 SubTask1 SubTask2 Structure Charts – Data Flow • An upward arrow indicates that the data value has been set inside the task and is being passed out for use by other tasks • A downward arrow indicates a data value previously set in some other task is now being passed into this task • Data may also be passed both into a task (downward arrow), modified, and passed back out again (upward arrow).

  36. main Result Data Data Result Get_Input Process_Data Display_Results Sample Structure Chart • Given a generic program that reads some data from the user, runs some calculations using that data, and displays results to the user, the structure chart could look like this:

  37. main Allow1, Allow2 Age1, Age2 Age1, Age2 Allow1, Allow2 Get_Ages Calculate_Allowances Display_Allowances Structure Chart: Sequential Program • Using our previous sequential program design example (calculate the two childrens’ allowances, based upon 75¢ per year-age), the structure chart might be:

  38. Summary – Structure Charting • Put the name of the program in a rectangle root of an upside-down tree. • Determine the main subtasks that must be performed by the program to solve the problem. • Put main subtasks in rectangles below the root, and draw a connecting line from the root to each subtask.

  39. Summary – Structure Charting • Examine each subtask individually, and break them down into even smaller tasks • Put subtasks in rectangles below the task that they are part of, and draw a connecting line from task to subtask. • Repeat until the BOTTOM TASKS of the tree are VERY SIMPLE to complete

  40. All Done for Today LBLOrg Chart • In Orgs or SW-Programs → Form FOLLOWS Function

  41. Engr/Math/Physics 25 Appendix Time For Live Demo Bruce Mayer, PE Licensed Electrical & Mechanical

  42. Yet More Org Charts

  43. CIA Org Chart (not secret)