0% found this document useful (0 votes)
9 views

Num Method 02 Structured Programming MAE284 SP20

Uploaded by

Isaac Thales
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Num Method 02 Structured Programming MAE284 SP20

Uploaded by

Isaac Thales
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Lecture 2: Structured Programming

MAE 284
Numerical Methods
R. N. Tantaris

1
MATLAB Basics
• Basic navigation in the command window
– Enter key – always takes you to the command prompt.
>> ( Also hit enter to execute a command)
– Up and Down arrow keys – Scroll through entries in
the MATLAB command history window.
– Backspace and Delete keys – used to edit command
lines.
– Tab key – smart recall, completes previously typed
functions after typing the first few letters.
– clc – command used to clear the MATLAB command
window. (The use of this command is also recorded in
the command history)
2
MATLAB Basics
• Basic arithmetic operations: multiplication of two decimals.
Note: the default
decimal display in
MATLAB is four
decimal places. This
may be changed using
the format command.

3
MATLAB Formatting
• Some Basic Formatting Commands:
– format short – 4 decimal places (default)
– format long – 16 digits
– format short e – five digits (4 decimals) plus exponent
– format long e – 16 digits (15 decimals) plus exponent
– format bank – 2 decimal digits
– format compact – removes extra blank lines
• Other formatting options described in Chapra
page 27 or in MATLAB help (type help
format)
4
MATLAB Basics

• Using several of the


format commands
with the previous
problem
– format compact
– format long

5
MATLAB Basics
• Work Session Commands:
1. clear – removes all variables from memory. Be careful
using clear!!! You can loose all of your data!
2. clear var1 var2 – removes ONLY the specific
variables var1 and var2 from memory.
3. exist(‘name’) – determines if a file or a variable
exists with the name ‘name’.
4. quit and exit– closes the MATLAB program.
5. who – lists the variables in current memory.
6. whos – lists the current variables and sizes, and indicates
if they have imaginary parts.

6
MATLAB Basics
6. : - the colon generates an array of equally spaced elements.
7. , - the comma separates array elements and multiple
commands.
8. ; - the semicolon suppresses screen printing and also denotes
a new row in an array.
9. … - ellipsis are used for line continuation.
10. Ctrl-C, Ctrl-Break – Stops execution
of a program
11. And my favorite command, why

7
MATLAB Basics
• Two variables are defined and added below:
Note: the comma (or a
semicolon) is used to
separate multiple
commands (e.g. the
definition of the two
variables)

Note: once the


variables are defined,
they may be used in
calculations or
algebraic expressions.

8
MATLAB Basics
• Built in variables and constants:
1. ans – most recent answer (can easily be
overwritten)
2. eps – specifies accuracy of floating point
precision.
3. i, j – either may be used for the imaginary unit.
4. Inf – infinity.
5. NaN – indicates an undefined numerical result.
6. pi – the number pi.
• Elementary function syntax may be found on page 35-
37 of Chapra.
9
MATLAB Basics
• One of MATLAB’s great strengths is it’s ability to handle
arrays (vectors and matrices). For example, to define a vector
in MATLAB one would do the following:
y = [2, 8, 14, 20]
Where the elements in the vector are separated by spaces or
commas. Remember, the order of the elements is important!
• A vector with equally spaced elements may be created by use
of the colon as: start_value : increment : end_value
For example, a=1:0.1:10 creates a vector from 1 to 10 in steps
of 0.1,
[1.0 1.1 1.2 1.3 1.4 1.5 … 9.8 9.9 10]
Note: x = 0:10 creates an array from 0 to 10 in steps of 1.
• In both cases, we created a row vector (one row with
multiple columns).
10
MATLAB Basics
• An example of the definition and subtraction
of two vectors:

11
MATLAB Basics
• An array index is used to
locate a certain element in
a vector. For example,
x(3), represents the third
value in the vector
defined as x.

• The length function is


used to determine the
number of elements in a
vector.
length(x)
will return the number of
elements in the vector x.
12
MATLAB Basics
• A column vector (one column
and multiple rows) is created
by separating elements by the
use of a semicolon (;).
x=[2; 7; -5]
creates a column vector with
three elements (rows).
• Vectors are transposed using
the single quote ( )
13
Built-in Functions
• A scientific calculator uses built-in functions
such as cos, ex, log, and sin-1.
– These operate on the number being displayed.
• These functions (and many more!) are available
in MATLAB.
– The value to be operated on must be specified
• The built-in functions available in MATLAB
can be found in online help
14
Structured Programming
• Structured programing (or modular programming)
is a technique for designing programs which uses a
logical modular structure to simplify writing,
reading, modifying, and reusing the program.

• A module is a group of related statements, each


having a single entry and a single exit point.

• Control is passed downward through the structure of


a main program from module to module in a top-
down design model.

1
5
Structured Programming
Sequential execution: First execute
Module 1, then execute Module 2

Module 1

Module 2

Execute Module 1 AND Module 2


16
Structured Programming
Conditional execution: execute
Module 1 or execute Module 2

Module 1 Module 2

Execute Module 1 OR Module 2


17
Structured Programming
Repeated execution:
execute module 1 and check
a condition.
Module 1
If the condition is true,
execute module 2 and start
over. ?
Otherwise, continue on to
the rest of the program.
Note that Module 1 is always Module 2
executed at least once but Module 2
is only executed if the condition is
true. 18
Advantages of Structured Programming
1. Structured programs are easier to write because
the programmer can study the overall problem
first and then deal with the details in individual
modules.
2. Modules (e.g. functions) written for one
application can be used for other applications
(this is called reusable code).
3. 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.
1
9
Advantages of Structured Programming
4. Structured programming is effective in a teamwork
environment because several people can work on a
common program, each person developing one or
more modules.
5. Structured programs are easier to understand and
modify, especially if meaningful names are
chosen for the modules and if the documentation
(Comments!) clearly identifies the module’s task.

2
0
Structured Programming
• In MATLAB, modules can be built-in or user-
defined functions.
• Examples of modules include:
– Modules (aka Blocks) – sequence of sequentially
executed statements (a collection of related statements)
– Conditional statements – statements that are
executed based on some condition (e.g. if x > 0.5, y = 1.
Otherwise, y = 0).
– Loops – repeated execution of a module (block of code)
– Subroutine or function calls
• We will discuss the first three types of modules today.

2
1
Terminology
• Flow Chart – graphically shows the structure of a
program
• Pseudocode – the structure of a program written in a
generic way. Can be converted to any programming
language

• Functions – a standalone subprogram (portion of


code) that accepts inputs from other code and returns
value(s) (e.g. y = sin(x)) . We will cover these in
more detail in the next lecture.
• Intrinsic Functions – (also called built-in functions)
are functions that are built into the programming
language. 2
2
Flowcharting
• Flowcharts are used in designing
or documenting a process or
program
• Flowcharts consist of blocks
connected by arrows.
• The main types of blocks are:
• Processing or execution
(rectangles)
• Decision or conditional
(diamonds)
• Loops
2
3
Flow Charts
Symbol

Terminal - Beginning or end of a program


Flow Lines - Flow of logic

Execution Statements - Calculations or data manipulation


Input/Output - Input data/output information
Conditional - Comparison, question, or decision (e.g if or
while statement) that determines path to be followed
Junction - Confluence of flowlines
Off-page Connector - break that is continued on a new
page
Count-controlled loop - loops (e.g. for loop or do loop)
that repeat a predetermined number of times
5
Flow Charts
x=0; Start
for k=1:1:10
x=x+2*k;
x=0
end

k=0
k<11
k=k+1

This is the
FOR loop x=x+2*k
If 𝑘 ≥ 11
exit FOR loop and
continue to next step
Examples

2
6
Statement Types
• Other than basic processing or execution statements
like x = 4 + 2. There are two main types of
statements:
• Conditional Statements (ask a question)
• If/Then
• If/Then/Else
• If/Then/Elseif/Else
• Loop Statements
• While loops
• While/Break loops
• For loops
Conditional Statements
• Conditional statements are statements that compare
two or more things in order to make a decision.
• Example: if (x < xmax), …
• 3 main types: If/Then, If/Then/Else,
and If/Then/Elseif/Else
if (x < xmax) then
if (x < xmax) then
Done = True
Done = TRUE
end
elseif (y > ymin)
if (x < xmax) then Done = MAYBE
Done = TRUE else
else Done = FALSE
Done = FALSE end
end
Logical (Boolean) Operators
• Logical or Boolean (or relational) operators are used
to compare two things.
• The result of using these is either TRUE, represented
as a 1 or FALSE (0) MATLAB
• Relational operators Notation
– Less than A < B
– Greater than A > B
– Less than or equal to A <= B
– Greater than or equal to A >= B
– Equal to A == B
– Not equal to A ~= B
9
Logical (Boolean) Operators
• Example: >> A = 1 >> A = [1 2 3 4]
>> A = 5; >> B = 0 >> y = A > 2
>> B = 6; >> x = A&B y =
>> x = A > B x = 1×4 logical array
logical logical 0 0 1 1
0 0
Boolean – a data type
>> class(x) >> x = A|B with only two possible
ans = x = values, in this case True
'logical' logical (1) or False (0). In
1 Matlab, they are
considered to be a logical
data type. 9
And, Or, Not, and Exclusive Or
Truth Table
True = 1, False = 0

Input(s) NOT AND OR XOR


MATLAB
A B ~A A&B A|B xor(A,B)
notation
0 0 1 0 0 0
0 1 1 0 1 1
1 0 0 0 1 1
1 1 0 1 1 0

31
If/Then Statement
Pseudocode
IF b is not 0 THEN
r1=-c/b
ENDIF

MATLAB

Note: a block can contain a single


statement, hundreds of statements, and
even other condition statements. 3
2
If/Then/Else Statement
Pseudocode
IF a < 0 THEN
b=sqrt(abs(a))
ELSE
b=sqrt(a)
ENDIF

MATLAB

33
Pseudocode
If/Then/Elseif/Else IF class = 1 THEN
x=x+8
ELSEIF class < 1
x=x-8
ELSEIF class < 10
x=x-32
ELSE
x=x-64
ENDIF
MATLAB

34
Matlab Bug & Checking Your PDF
• There is a known bug in Matlab starting back in version
R2017a. If you publish your program on a non-lab PC (e.g. your
personal laptop) and your "default path" for saving your figures
for the PDF has a space in it, Matlab will generate an error and
will not include the plots in the PDF.
• The error will look like this:
• [ERROR] FOUserAgent - Image not found. URI: C:/Users/FirstName LastName/AppData/Local/Temp/xxx.bmp. (See position -
1:-1)
• [ERROR] FOUserAgent - Image not found. URI: C:/Users/FirstName LastName/AppData/Local/Temp/xxx.bmp. (No context info
available)

• Note the space between FirstName and LastName in the path to


the bitmap (xxx.bmp) file.
• If you have this problem, the simplest solution is to publish your
code using a lab computer in N278, N214, or N216.
35
Schedule

36
Reminder
• Bring clickers next class/lab. Haven’t bought yet,
forgot to bring, no batteries, etc. are not valid excuses.

37

You might also like