Vous êtes sur la page 1sur 10

Melbourne School of Engineering

Engineering Systems Design 2

Workshop Four (W04)


Programming: Input-Output, Computations and Functions

Welcome to Workshop 4 for Engineering Systems Design 2. The goal of this workshop is to
practice your MATLAB skills to prepare you for a project spanning three workshops that in-
volves designing various aspects of a simulation game. There is no assessment for this workshop,
although successfully completing Part B is vital for the next two workshops.

Learning Objectives

The exercises in this workshop will give you experience in:

Using MATLAB command line interpreter for dierent (computational and non-computational)
tasks.

Using MATLAB programming environment to write and execute programs.

Writing MATLAB scripts that perform basic input/output (input from the keyboard and
output to the console).

Writing programs to perform basic computational tasks, using variables, expressions and
assignment statements.

Writing MATLAB functions to perform computational tasks.

Part A (General)
1. (a) Enter the following into MATLAB

x = 7;
fprintf(The value of x is %d\n,x)
fprintf(1,The value of x is %d\n,x)

and observe the result. What does the fprintf function do?
(b) Now enter the following into MATLAB

fprintf(The value of x is still %f\n, x)

1
and observe the result. How does the dierent specier (%d, %f) change the output?
(c) Enter the following into MATLAB

x = 7.5870;
fprintf(x can be displayed as : %1.4f\n,x)
fprintf(or this : %20.4f\n,x)
fprintf(or even this : %7.2f\n,x)

and observe the results. Describe the eect of the values x and y in the format
specier %x.yf for the fprintf function.
(d) Enter the following commands in MATLAB
i. abs(3)
ii. abs(-5)
iii. abs(3 - 4i)
What does the abs function do? Type help abs to conrm your answer.

2. (a) Type in the following commands into MATLAB

A=[1 2 3 4]
B=[1; 2; 3; 4]
C=[2 3 7 9 10 12 14]
D=[2 3 3;7 2 2]

Write down the outputs of the length() and numel() functions for each of the above
input variables. Can you gure out what is the role of the length() and numel()
functions in MATLAB?
(b) Write down what is output from the following commands in MATLAB (assuming
all variables are as dened in (a) above) then type them in to check
i. A(4)
ii. A+B
iii. D(2,:)
iv. A^2
v. C.^2
vi. C(length(A))

3. This question will help you better understand the examples presented in the lectures
through trying them out yourself.

(a) Use the following steps to write and run the HelloWorld program (a script le
HelloWorld.m) presented in the lectures.
Write and save the program:

2
Change the directory to where you want to save the program le.
Choose File >New-Script and the editor will open.
Type in the program lines in the editor.
Choose File >Save As and enter the name of the le as HelloWorld and save
the program will be saved in a le named HelloWorld.m which is a MATLAB
script le. You may choose any name for the le but always use a meaningful
name.
Run the program:
Click on the green arrow on the top menu to run the program OR enter Hel-
loWorld on the command window prompt.
Observe the output on the command window.
(b) Run the following examples from the lecture slides, and understand how the pro-
grams work.
FormattedOutput.m
FahrenheitToCelsius.m
CylinderSurfaceArea.m

4. Implement and test the following as MATLAB scripts.


(Following problems are from MATLAB A Practical Approach, Stormy Attaway)

(a) Write a script that will prompt the user for an angle in degrees. It will then calculate
the angle in radians, and then print the result. Note: radians = 180 degrees.
(b) On average, people in a region spend 8 to 10% of their income on food. Write a
script that will prompt the user for an annual income. It will then print the range
that would typically be spent on food annually. Also, print a monthly range.
(c) Wing loading, which is the airplane weight divided by the wing area, is an important
design factor in aeronautical engineering. Write a script that will prompt the user
for the weight of the aircraft in kilograms, and the wing area in meters squared, and
will calculate and print the wing loading of the aircraft in kg/m2.

5. Implement and test the following MATLAB functions.

(a) The velocity of a moving uid can be found from the dierence between the total
and static pressures Pt and Ps . For water, this is given by V = 1.016Pt Ps . Write
a function, calc_velocity, that will receive as input arguments the total and static
pressure and will return the velocity of the water.
(b) For a project, some biomedical engineering students are designing a device that will
monitor a persons heart rate while on a treadmill. The device will let the subject

3
know when the target heart rate has been reached. A simple calculation of the target
heart rate (T HR) for a moderately active person is:

T HR = (220 A) .6,

where A is the persons age. Write a function,calc_THR, that will calculate and
return the T HR, given the age.
(c) The Law of Cosines relates the lengths of the sides of a triangle to the interior angles
:
c2 = a2 + b2 2ab cos()
where the variables are dened in Figure 1. Write a MATLAB function cos_rule
that, given two of the side lengths and the angle between them in degrees, calculates
and returns the length of the third side.

Figure 1: Cosine rule

(d) The present value of an annuity (a yearly sum of money) may be computed from
the formula [ ]
1
P = (A/i) 1
(1 + i)n
where A is the annuity (in $/year), i is the nominal yearly interest rate (in decimal
form), n is the number of years over which the annuity is paid and P is the present
value ($).
For example: If i = 0.15 (15%), A = $100/year and n = 10 years then P = $501.88.
Write a MATLAB function calc_annuity(A,i,n) that takes the annuity amount,
the nominal yearly interest rate and the number of years and returns the present
value P in dollars.

6. (Problem 12.3 from Brockman)


Consider the following function, seven, that returns the value 7 for any inputs x and y:

4
function z = seven(x,y)
% always returns the value 7
x = 7; y = x; z = y;

If we dene four variables w, x, y, z in the Command Window and then call the function
seven(x,y), what will be the values of these variables after the function call returns?

>> w = 0;
>> x = 1;
>> y = 2;
>> z = 3;
>> w = seven(x,y)

Figure this out without running the program then type it in and see if you were correct.

5
Part B (Project)

Overview

The project over the next three workshops is to progressively design an artillery video game1 .
The game to be designed here is a very simple version involving two players, who each have a
turret that is xed at a random location in a two-dimensional setting. Each player attempts to
hit the others turret with a projectile launched from their own turret by adjusting the angle
and ring velocity of their turret before each shot.

Upon starting the game, each players turret is placed at a random position in the two-
dimensional landscape (see Figure 2). The game is round-based, which in this case means
that for each round both players enter their launch parameters via a Graphical User Interface
(GUI) and the turrets then re their projectiles. The game models and plots the trajectory of
the projectiles and determines if one of the turrets has been hit. If there is no winner, players
are then free to select new parameters in an attempt to improve their shooting and come closer
to hitting the opponent. Player 1 is on the left of screen and Player 2 on the right.

Figure 2: The battleeld

A owchart for the operation of the game is given in Figure 3. Actions are represented by
rectangles and decisions by diamonds. Most of the skeleton of the game is completed, but over
the next three workshops you will be developing code for three specic sections of the game
indicated in the owchart :

Workshop 4 : Calculation of the turret position for refreshing the screen (yellow block)
1
Scorched Earth, released in the early 1990s, is one of the most popular shareware versions of this genre of
artillery game.

6
Workshop 5 : Implementation of the projectile dynamics and rules of the game (orange
blocks)

Workshop 6 : Development of an algorithm to automatically choose launch parameters


to be used by a computer player (purple block)

You will be assessed on your implementation of the game in Workshop 6.

Calculation of the gun barrel position for refreshing the screen

The task for today is to write a function that calculates the coordinates of the gun barrel given
information about the location of the turret, its width, the barrel length and the launch angle
(in degrees). When a player enters a new launch angle , the new gun barrel coordinates will
be calculated by your function and the display refreshed.

The geometry of the turret for Player 1 is given in Figure 4. The anchor point of the turret
is located at (xpos,ypos) with all other measurements in terms of the turret width (tw),
barrel length (bl) and . Player 2s turret faces in the opposite direction - however the lower
left point is still the anchor point. The function that you develop must calculate and return
the coordinates (x1,y1) and (x2,y2).

The function is called as follows :

[x, y] = calc_barrel_pos(xpos, ypos,


turret_width, barrel_length, theta, player)

The sets of coordinates [x, y] that your function needs to return are the start and end coor-
dinates of the gun barrel in Euclidean coordinates. For instance, x = [3 7] and y = [2 5]
means that the barrel starts at the point (x1,y1) = (3,2) and ends at (x2,y2) = (7,5).

The variable player is equal to 1 for Player 1 or -1 for Player 2. You will need to use this
variable to determine which players barrel you are calculating and use the appropriate set of
equations.

Task 1 : Determining the equations

By hand, for Player 1, determine the equations that dene the beginning and end of the gun
barrels position in terms of the variables xpos, ypos, turret_width, barrel_length and
theta.

Repeat for Player 2.

7
Task 2 : Writing the function

Once you have the equations for the gun barrel coordinates, write the function calc_barrel_pos
using the same ordering of arguments as above. This function MUST be saved with the lename
calc_barrel_pos.m. Use the argument player to determine which of the sets of equations to
use from Task 1 to calculate the gun barrel positions.

Task 3 : Testing the function

Test your function by calling it with the inputs

xpos 25
ypos 30
turret_width 20
barrel_length 10
theta 35 degrees
player -1

Check with your tutor that your values for [x, y] are correct.

Make sure that you have your code saved in a secure location as you will need it
for the next workshop.

8
Draw barrel
Initialise game
parameters

Get user input


Start the
sim?

Is
t > tmax ?

Calculate pro-
jectile positions

Plot projec-
tile positions

Out of
bounds?

Have a
winner?

Increment t

Set winner = 0

Set winner
= -1 or 1

Game
mode?

Calculate
parameters

Yes

Print result
No

No

No

No

Yes

User

AI
Figure 3: Flowchart for the turret game
9

Yes

Yes
tw/3

tw/4

tw/2

(xpos,ypos)

Vous aimerez peut-être aussi