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

Num Method 03 Functions MAE284 SP20

Uploaded by

Isaac Thales
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Num Method 03 Functions MAE284 SP20

Uploaded by

Isaac Thales
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Lecture 3: Functions

MAE 284
Numerical Methods
R. N. Tantaris

1
SSC Tutors

SSC Tutors
• Keona Banks
• Taylor Kerlin
• Nathen Munyak
• Gui Coleta
• Nat Mann
• Jude Smith

2
Clicker Channel
• Set your clicker channel to 45.

4
First Problem
Clicker Channel = 45
Select choice “C” below:
A. Wrong Answer
B. Wrong Answer
C. SELECT ME
D. Wrong Answer

8
Second Problem
• Everyone select “C”
• Now suppose we decided to change our
minds and wanted to resubmit. As long
as polling has not closed we can simply
type “B” to change answer.
A. Wrong Answer
B. But correct to this
C. Select First
D. Wrong Answer

9
Timed Problem
Most problems I will have on a timer. Select “D” from
the choices below before the timer reaches zero and the
polling closes.

A. Not this one


B. Not this one
C. Not this one
D. Quick-This one

10
Multiple correct answers
Which of the following are colors?

A. Red
B. Green
C. Blue
D. Five

11
Statement Types
• Other than basic processing or execution
statements like x = 4 + 2. There are two main
types of statements:
• Conditional Statements
• If/Then
• If/Then/Else
• If/Then/Elseif/Else
• Loops Statements
• While loops
• While/Break loops
• For loops
Loops
• Loops are used to repeat a block of statements
multiple times.
• 3 main types: While loops, While/Break loops
and For loops
while (x < xmax)
x = x+1;
while (1)
end
x = x+1;
if (x >= 10)
break
end for (k=1:0.1:10)
end x(10*k)
end
Loops
• While loops are used to execute a block of
statements an unknown number of times.
• While loops terminate based on some condition.
• For loops are used to execute a block of statements
for a fixed number of times (e.g. for k =
1:100, …) or for every value in the increment
variable (e.g. for k = 0:0.1:100, …)
• The block of statements can contain any valid
statements including conditional statements and
even other loops.
• When there are loops inside of loops, we call this
nested loops.
While Loops
Pseudocode
Start with c=1
WHILE 1+c > 1 THEN
divide c in half
ENDWHILE
eps = 2*c

MATLAB

15
While/Break Loops
WHILE Pseudocode
increase i by 1
IF i is 10 or more BREAK
let j = i times x
ENDWHILE

MATLAB

16
For Loops
Pseudocode
FOR i = 1 to 10 by 2’s
increase x by i
ENDFOR

MATLAB

17
Flowchart for Problem Resolution
Is it
YES working?
NO
Don’t mess with it
Did you
YES
mess
with it?
You IDIOT!!!
NO
Will it
Anyone YES
else You’re screwed! YES blow up in
your
know? hands?

NO NO Can you NO
Hide it blame anyone Look the other way
else?
YES

NO PROBLEM
Factorial
Flow Diagram Pseudocode
Input
N = number to evaluate
factorial
M=1
F=1
FOR M = 1 to N
F=F*M
ENDFOR

Output F
19
Factorial
Flow Diagram Create a table with all of the variables.
For this example, let N=7.

Iteration N M F F=F*M M==N


0 7 1 1
1 7 1 1 1 No
2 7 2 1 2 No
3 7 3 2 6 No
4 7 4 6 24 No
5 7 5 24 120 No
6 7 6 120 720 No
7 7 7 720 5040 Yes

20
“Average” Program
num = number of items Example: list = [5 2 6 8 4]
list = values to be averaged

sum =
initialize sum = 0 Iteration num i i>num sum sum+list(i)
0 5 -- 0
1 5 1 No 0 0+5 = 5
2 5 2 No 5 5+2 = 7
3 5 3 No 7 7+6=13
4 5 4 No 13 13+8 = 21
5 5 5 No 21 21+4 = 25
Average = sum/num 6 5 6 Yes 25 Exit loop

Display Average Average = 25/5 = 5


21
Using MATLAB
Input:
list = vector with numbers
num = length of list
sum = 0
FOR I = 1 to num by 1’s
sum = sum + listi
END
average = sum/num
Output: average

% lecture03_example – demonstration of calculating average

list = [5 2 6 8 4]; % List of numbers to average


num = length(list); % Number of values in the list
sum = 0; % Variable to hold current sum
% Accumulate sum of values
for i = 1:num
sum = sum + list(i);
end
average = sum/num % Calculate the average
Functions
• A script is simply a sequence of Matlab
commands collected in a file (an M-file or
script file).
• Suppose you needed to calculate the
factorial of the following numbers: 2, 5,
10 , 20, 50, and 100.
• One way to do this would be to copy the
lines of code we have written previously 6
times (once for each number) and change
the value of n each time.
• A better way would be to call a function
from within a loop to calculate the
factorial. Especially if the list is long.
Functions
• This is one reason for using functions, it can greatly simplify
writing a program and often results in shorter programs.
• Functions are also useful for modular programming.
• Another benefit of functions is reusability, once the function
is written, it can be used by other programs.
• Functions can serve as a “black-box” to hide the code inside
from the user.
• As a result, variables inside functions can have different values
from variables with the same name in the workspace or other
functions.
• There are two types of functions:
– A standard named function written in an m-file
– An anonymous function
Functions
• The standard type of function has a name:
– e.g. sin, tan, atan, , average, factorial, ralph, grades_spring2018, …
– Any legal variable name is OK
– The function name MUST be the same as the filename. For example,
the function mycalc must be named mycalc.m.
• Functions have inputs (parameter/argument list)
– Can be numbers, vectors, arrays, strings, variables, etc.
– When defining or using the function the parameters immediately follow
the function name and are in parentheses
• Functions have outputs (return values)
– Can be numbers, vectors, arrays, strings, etc.
• Functions can call other functions. The calling functions are
called primary or main functions. The functions that are called
are subfunctions.
Function Declaration
The function declaration must be the first non-comment line in the file. For
example

1. One input, one output:


function [area_square] = square(side)

2. Brackets are optional for one output, parenthesis for inputs are always
required:
function area_square = square(side)

3. Multiple inputs, one output:


function [volume_box] = box(height,width,length)

4. One input, two outputs:


function [area_circle,circumf] = circle(radius)

5. No output (e.g. produces a plot):


function sqplot(side) 28
Structure of a Function
1. Function declaration:
function [out1, out2, …] = mycalc(in1, in2, …)
2. Header comments section (can precede the function declaration)
– The name of the program and any key words in the first line.
– The date created, and the creators' names in the next lines.
– The definitions of the variable names for every input and output
variable. Include definitions of variables used in the
calculations and units of measurement for all input and all
output variables, if applicable!
– The name of every user-defined function called by the program.
3. Input section
– Any processing or error checking of the input.
4. Calculation section
5. Output section
– Any code for displaying the output on the screen.
29
Anatomy of a Function
% MY_NED2ECEF - Convert vector from NED to ECEF coordinate frame.
% R. N. Tantaris
% May, 2006
%
% SYNTAX:
% v = ned2ecef(u,lat,lon) Header
% Where
% u = vector in NED coordinates. (Comments)
% lat = latitude in degrees.
% lon = longitude in degrees.
% v = vector in ECEF coordinates.
function v = my_ned2ecef(u,lat,lon)
Function
% Convert lat and lon to radians.
% -------------------------------
Declaration
lat = lat*pi/180; Input (processing)
lon = lon*pi/180;
% Create DCM
% ----------
DCM = [(-sin(lat)*cos(lon)) (-sin(lat)*sin(lon)) cos(lat)
-sin(lon) cos(lon) 0
(-cos(lat)*cos(lon)) (-cos(lat)*sin(lon))
DCM = DCM';
-sin(lat)]; Calculation
% Compute vector in ECEF.
% -----------------------
v = DCM*u; 30
Function Example – sqArea
L = Length of side
Pseudocode
Input L
A = L2

A = L^2
Output A

Output A

MATLAB
function [A]=sqArea(L); >> A=sqArea(4)
% Computes area of square
with side length L. A = 16
A = L^2; >> sqArea(5)
ans = 25

31
Function Example – drop
g = gravity
v0 = initial velocity
t = time

vel = g*t+v0
dist = 0.5*g*t2+v0*t

Output dist, vel

Pseudocode
MATLAB
Input g, v0, t function [dist,vel]=drop(g,vO,t)
% Computes the distance traveled,
vel = g*t+v0 % velocity of a dropped object,
Anticipating thatg,t will be an array, so
% given gravity
dist = 0.5*g*t^2 % theusing element-by-element
initial velocity vO, and
+v0*t % theoperations
time t.
vel = g*t + vO;
dist = 0.5*g*t.^2 + vO*t;
Output dist, vel 32
Function Example (con’t)
>> [distance, speed]=drop(32.2,10,5)
distance = 452.5000
speed = 171

>> drop(32.2,10,5)
ans=452.5000

>> [distance, speed]=drop(32.2,10,0:0.5:5)

33
True Logical Operators
True = 1
• 5<4 & 8<10 False False = 0
• 5<4 | 8<10  True
Inputs and or not xor
False A B A&B A|B ~A xor(A,B)
0 0 0 0 1 0
0 1 0 1 1 1
1 0 0 1 0 1
1 1 1 1 0 0

For the condition to be True:


and (&): both statements must be true
or ( | ): at least one statement must be true 34
Logical Operators
For the condition to be True:
and (&): both statements must be true
or ( | ): at least one statement must be true

• Example 1 • Example 2
x = 1; x = 1;
if (5<4 & 8<10 ) if (5<4 | 8<10 )
x = 5; x = 5;
end end
The value of x is 1 The value of x is 5.

35
Question #4
function C=runme(A,B)
if A<B-5 | B>A*2
C=4;
else
C=8;
end
Given that A=4 and B=9 what
will the output, C, of the
function runme be?
A. 0
B. 4
C. 8
D. Other
36
Flow Diagram WS3 Example
• Takes two inputs and divides one
by the other unless second term is
n = term in numerator zero.
d = term in denominator
• Instead of requiring the user to
input information in the
TRUE FALSE command window we can have
if d=0
them input the information when
the function is called.
frac =
frac= n/d
‘Cannot
divide by
zero’ function frac=divide(n,d)
if d==0
frac = ‘Cannot
divide by zero’;
else
Output frac frac = n/d;
end
37
McDonalds is a Function
• Give them: INPUT
– A list of what you want
– Cash

• You get: OUTPUT


– The ordered items
– Change
McDonalds as a MATLAB Function
function Output = FunctionName(Input)
[Items, Change]=McDonald(Order, Money)

0
_ Hamburger
1
_ Cheeseburger
0
_ Chicken Sandwich
2
_ Big Mac
0
_ Fish Sandwich
0
_ Fries – small
1
_ Fries – medium
0
_ Fries – large
1
_ Coke
0
_ Mello Yello
0
_ Shake
4 2 2 2 2
Bubble Sort 2
 
4
 
4
 
4
 
4
 
• Assume the list has ‘n’ 5
1
5
1
5
1
1
5
1
3
         
numbers 3 3 3 3 5

• Start at the top of the list and 2


 
2
 
2
 
2
 
2
 
4 4 1 1 1
         
exchange the top two 1 1 4 3 3
3 3 3 4 4
numbers if the second is less          
5 5 5 5 5
than the first
2 1 1 1 1
         
• Repeat for elements two and 1 2 2 2 2
3 3 3 3 3
three 4 4 4 4 4
         
5 5 5 5 5
• Repeat the process for the
1 1 1 1 1
total of ‘n-1’ pairs  
2
 
2
 
2
 
2
 
2
         
• Repeat the previous three 3
4
3
4
3
4
3
4
3
 4  40
steps a total of ‘n-1’ times.  
5
 
5
 
5
 
5
 
5
Flow Chart
for Bubble
Sort

yes

no
41
Pseudocode
Input: list
n = length(list)
FOR j=1 to n-1 by 1’s
FOR k=1 to n-1 by 1’s
IF list(k+1)<list(k) THEN
swap=list(k)
list(k)=list(k+1)
list(k+1)=swap
ENDIF
yes
ENDFOR
ENDFOR
Output: list no
42
Bubble Sort in MATLAB
Pseudocode
Input: list
MATLAB
n = length(list) function [list]=bubble(list)
FOR j=1 to n-1 by 1’s n=length(list);
for j = 1:n-1
FOR k=1 to n-1 by 1’s for k=1:n-1
IF list(k+1)<list(k) THEN if list(k+1)<list(k)
swap=list(k) swap = list(k);
list(k) = list(k+1);
list(k)=list(k+1) list(k+1) = swap;
list(k+1)=swap end
ENDIF end
end
ENDFOR
ENDFOR
Output: list
43
Anonymous Functions
• An alternative way in MATLAB to define a simple
mathematical function is to use anonymous functions.
• Unlike the previous type of function we have discussed,
anonymous functions do not have a name (hence anonymous)
• Anonymous functions can be defined in the workspace or
inside another program. The anonymous function has to be
defined before it is used. For example,
poly3 = @(x) 3*x.^3 + 5*x.^2 – 2*x + 1
poly3(2)
ans = 41
3 2 3 + 5 2 2 − 2 2 + 1 = 41
• The variable poly3 in the workspace is called a function
handle.
Anonymous Function
What is the result of the following?
>> add = @(x,y) x+2*y;
>> a=1; b=2;
>> add(a,b)
Rank Responses
1
2
3
4
5
6 45
Matlab Plotting Demo
• Basic plotting commands
– figure – xlabel, ylabel, zlabel – axis
– plot – title – hold
– subplot – legend – grid
• Plots should always be labeled when possible. For example, if
you are plotting a function of x, you can label the x axis as
simply “x” and the y axis as “f(x)”. If you are plotting
displacement versus time, the labels should be “displacement“
and “time”.
• Axis labels should include units if possible.
• If more than one plot is generated in the same figure (not
subplots), use the legend command to distinguish between
them.
46
Matlab Plotting Demo
title('MAE 284, Homework 1, Problem 2, Part a')

figure(1)
t = 0:0.01:5;
y = exp(-t);
plot(t,y)

ylabel('f(t)')

xlabel(‘t')
47
Matlab Plotting Demo
title('MAE 284, Homework 1, Problem 2, Part a')

legend('y(t) = e^{-t}', …
'z(t) = 0.2t+0.1', …
'Location','NorthWest')

ylabel('Amplitude')

figure(2)
t = 0:0.01:5;
z = 0.2*t + 0.1;
plot(t,y,'b',t,z,'m')

xlabel('t')
48
Matlab Plotting Demo
figure(3)
x = 0:0.01:10*pi;
y1 = cos(x);
y2 = sin(x);
y3 = cos(x) + sin(x);

subplot(311)
plot(x,y1,'b')
ylabel('cos(\theta)')
title('MAE 284, Homework 1, Problem 2, Part a')

49
Matlab Plotting Demo

subplot(312)
plot(x,y2,'b')
ylabel('sin(\theta)')
50
Matlab Plotting Demo

subplot(313)
plot(x,y3,'b')
ylabel('cos(\theta)+sin(\theta)')
xlabel('\theta') 51
Matlab Example
function [] = STK_EandA_re(origin_file,ephem_file,att_file)

% Function to determine ephemeris and attitude from list of data consisting of:
% time
% x, y, and z position
% x, y, and z velocity

% Opens file, reads contents, and closes file


fid = fopen(origin_file); This is an .m file that takes the
ephem = dlmread(origin_file);
fclose(fid); position and velocity of a
% Separates data for ease of access and identification missile from a text file and
t = ephem(:,1);
x = ephem(:,2); creates an ephemeris file and
y = ephem(:,3);
z = ephem(:,4); attitude file, which then can be
vx = ephem(:,5);
vy = ephem(:,6); imported into STK to plot the
vz = ephem(:,7);
trajectory.
% Determines normalized velocity vector for each time value
magnitudes = sqrt(vx.^2 + vy.^2 + vz.^2);
vx_norm = vx./magnitudes;
vy_norm = vy./magnitudes;
vz_norm = vz./magnitudes;
.
.
.
52
Matlab Example
http://www.agi.com/products/engineering-tools

53
Student Success Center
• Tutors:
– Joel Bernard – Gui Coleta
– Noah Clanton – Keilah Fok
– Taylor Kerlin – Nat Mann
– Nathen Munyak
• Available in person or online.
• Go to https://www.uah.edu/ssc/tutoring to
make an appointment.

54
Student Success Center
• See them for efficient, effective tools in learning
– Is it better to always study in the same place?
– For a fixed amount of time, is it better to cram or spread
out studying for a test?
– When studying, is it is better to stick to a single subject or
study multiple subjects?
– What techniques improve retention for longer time periods?
– Do you learn better if someone shows you how to do
something or if you figure it out on your own?
– How do you know if you truly understand the material?

55
Did you understand today’s topics?
A. Yes
B. Mostly
C. A little
D. No
E. Need to review first

56

You might also like