Bruce Mayer, PE Registered Electrical & Mechanical Engineer

Bruce Mayer, PE Registered Electrical & Mechanical Engineer Bruce Mayer, PE Registered Electrical & Mechanical Engineer - Start

2019-03-14 0K 0 0 0

Bruce Mayer, PE Registered Electrical & Mechanical Engineer - Description

BMayer@ChabotCollege.edu. Engr/Math/Physics 25. Chp4 MATLAB. Programming-1. Learning Goals. Write MATLAB Programs That can MAKE “Logical” Decisions that Affect Program Output. Write Programs that Employ . ID: 756266 Download Presentation

Download Presentation

Bruce Mayer, PE Registered Electrical & Mechanical Engineer




Download Presentation - The PPT/PDF document "Bruce Mayer, PE Registered Electrical &a..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.



Presentations text content in Bruce Mayer, PE Registered Electrical & Mechanical Engineer

Slide1

Bruce Mayer, PERegistered Electrical & Mechanical EngineerBMayer@ChabotCollege.edu

Engr/Math/Physics 25

Chp4 MATLAB

Programming-1

Slide2

Learning GoalsWrite MATLAB Programs That can MAKE “Logical” Decisions that Affect Program OutputWrite Programs that Employ LOOPing ProcessesFor → No. Loops know a prioriwhile → Loop Terminates based on Logic CriteriaUse the MATLAB DeBugger to

Correct Errors (time permitting)

Slide3

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.

Slide4

Algorithm DefinedALGORITHM  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:

Slide5

Algorithmic OperationsSEQUENTIAL OPERATIONS → Instructions executed in orderCONDITIONAL 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 answerITERATIVE OPERATIONS (LOOPS): Control structures that repeat the execution of a block of instructions

Slide6

Structured ProgrammingSTRUCTURED 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.

GoTo

statements

Slide7

Structured Program AdvantagesStructured 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 perform just one task and thus it can be tested separately from the other modules.

Slide8

Structured Program AdvantagesStructured 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.

Slide9

Developing Computer Solns State the problem conciselyUse Math Eqns/Relns Whenever possibleSpecify the data to be used by the program. This is the “input

.” In physical Problems These are typicallyBoundary ConditionsInitial ConditionsConstraintsParametersSpecify the information to be generated by the program. This is the “output.”

Slide10

Developing Computer Solns cont Work through the solution steps by hand or with a calculator; Use a simpler set of data if necessaryTest for EXTREME cases withInput or Output = ±∞

, 0, ±1Write and Run the programCorrect Compile/Execution Time ErrorsMissing Comma or Parens, MisTyped Var names, etc.Correct

RunTime Errorse.g., NaN’s

, inf’s, Divide-by-Zero, Complex Numbers, etc.

Slide11

Developing Computer Solns cont 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

Slide12

Developing Computer Solns cont 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

Slide13

Effective Documentation Proper selection of variable names to reflect the quantities they representUse DESCRIPTIVE and/or LONG namesUse of comments within the programAlso helps CLARIFY the WRITING of the CodeUse of structure chartsLike an ORG Chart for

your Software ProgramStructure charts show how variables pass between modules in a computer program.

Slide14

Anatomy of a Structure Chart Module

the called module

Slide15

Example: Pizza Pricing ProblemWrite 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

Slide16

Effective Documentation cont Use of flowchartsEach 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

Slide17

FlowCharting Example

Basic House Painting

Note the Cascade of Decision-Diamonds

Slide18

Effective Documentation cont A verbal description of the program, often in pseudocode.Generic way of describing

an algorithm, without use of any specificprogramming languageHelps programmers to PLAN an algorithmNot an actual programming Language, but may borrow syntax from popular programming languagesStyles vary

Slide19

PseudoCode ExampleExample Problem: Calculate the bill when someone buys a specific no. of some item:PseudoCode:PROMPT for number of items being purchasedREAD number of items being purchasedPROMPT for price per itemREAD price per itemCALCULATE subtotalCALCULATE taxCALCULATE totalDISPLAY total

Slide20

PsuedoCode: Common Terms To Describe input, output, computations, etc., the following terms are often used:Input: INPUT, READ, GET Output: PRINT, DISPLAY, SHOWCompute: COMPUTE, CALCULATE, DETERMINE Initialize: SET, INIT Add one: INCREMENT,

BUMP, STEPDecisions: TEST, IF/THEN/ELSE, WHILE/DO

Slide21

PsuedoCode AlgorithmsEnsure that the the task is completely specifiedIssues to ConsiderWhat 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?

Slide22

Solve QuadraticEquation

PsuedoCode

Get

coeffs

a, b, & c

Let

d = b

2

− 4ac

If d < 0 print 'no real solutions' and go to step 5

Let X

1

= (−b + SQRT(d))/(2a)

Let X

2

= (−b − SQRT(d))/(2a)

Print X

1

and X

2

Stop

Slide23

PsuedoCode ExampleReal World Problem:Calculate the allowance for two children, based upon 75¢ per year-of-ageKnown ValuesPay Rate = 75

¢/yearInputsChild AgeCalculationsAllowance = Age x RateOutputsAllowances for each child

Slide24

PsuedoCode Example contCareful PseudoCode Algorithm:PROMPT for Age of Child1READ Age of Child1PROMPT for Age of Child2

READ Age of Child2CALCULATEAllowance for Child1 = [Age of Child1] x RateCALCULATE Allowance for Child2 = [Age of Child2] x RateDISPLAY Allowance for Child1DISPLAY Allowance for Child2

Slide25

Program Design - FlowChart Flowchart  a graphical representation of algorithms

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

Slide26

FlowChart Symbols – Calc’sCalculations (e.g. arithmetic expressions) are shown in rectanglesExample: Total = Cost + Tax

ExampleNum = Num + 1 add one to the current value of Num and make that the new value of Num

Total = Cost + Tax

Num = Num + 1

Slide27

FlowChart Symbols – In/Out PutData input and output are shown in parallelograms

Input  a read operation of data from a peripheral device

to memory e.g., a user typing in data

at a keyboard

READ Num

WRITE Num

Output

a write operation of data to a peripheral device from memory

e.g., data displayed to the monitor

Slide28

FlowChart Symbols – DecisionsDecisions are shown within Diamonds and specify a condition to be tested

Based on the condition being TRUE or FALSE, the next operation will be determined

A decision is composed of :

A conditionAn operation to be done if condition is TRUEPossibly an operation to be done if condition is FALSE

Gross > 50000

Rate = 0.31

Rate = 0.28

True

False

Slide29

FlowChart Symbols – Start/EndEvery algorithm starts somewhere and terminates somewhere

Every flowchart must have one start symbol and one end

symbolStart and

Stop symbols are ovalsA start symbol denotes the start of the algorithm

An end symbol indicates the algorithm has terminated

square = num x num

input num

print square

start

stop

Slide30

FlowChart ExampleSequential-FlowChart for the Previous Pseudocode Algorithm:

Allow1 = Age1 x Rate

input Age1

start

Print Allow1

stop

prompt Age1

Allow2 = Age2 x Rate

Print Allow2

input Age2

prompt Age2

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

Slide31

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

Slide32

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

Slide33

Structure ChartStructure charts are Hierarchical diagrams → A form of an “Org Chart”They diagram the OverAll program (organization) StructureThey show the Relationship between all the Tasks (workers) in the programThey indicate which Data

(Information) is shared by the tasks (workers)

Slide34

Creating Structure ChartsA large program design is first broken into tasksTasks are repeatedly divided into even smaller subtasksRectangles are used to represent tasks/subtasks within the programLines are used to hierarchically

connect the tasks/subtasksSubtasks are diagrammed below the task that they are part of

Task

SubTask1

SubTask2

Slide35

Structure Charts – Data FlowPassing of data between tasks is shown by arrows going up from or down to the task’s rectangle

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 taskData may also be passed both into a task (downward arrow), modified, and passed back out again (upward arrow).

Task

SubTask1

SubTask2

Data1

Data1

Slide36

Sample Structure ChartGiven 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:

main

Get_Input

Process_Data

Display_Results

Data

Result

Data

Result

Slide37

Structure Chart: Sequential ProgramUsing our previous sequential program design example (calculate the two childrens’ allowances, based upon 75¢ per year-age), the structure chart might be:

main

Get_Ages

Calculate_Allowances

Display_Allowances

Age1, Age2

Allow1, Allow2

Age1, Age2

Allow1, Allow2

Slide38

Summary – Structure ChartingPut 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.

Slide39

Summary – Structure ChartingExamine each subtask individually, and break them down into even smaller tasksPut 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

Slide40

All Done for Today

LBL

Org Chart

In Orgs or SW-Programs →

Form

FOLLOWS

Function

Slide41

Bruce Mayer, PELicensed Electrical & Mechanical EngineerBMayer@ChabotCollege.edu

Engr/Math/Physics 25

Appendix

Time For

Live Demo

Slide42

Yet More Org Charts

Slide43

CIA Org Chart (not secret)

Slide44

Slide45


About DocSlides
DocSlides allows users to easily upload and share presentations, PDF documents, and images.Share your documents with the world , watch,share and upload any time you want. How can you benefit from using DocSlides? DocSlides consists documents from individuals and organizations on topics ranging from technology and business to travel, health, and education. Find and search for what interests you, and learn from people and more. You can also download DocSlides to read or reference later.