A4

ENGR 17
Assignment 4 Conditionals
Due: next Tuesday
If you have not done the Ch4a drills listed in the powerpoint slides, please do those first. (don’t turn in)
Create the folder A4 on your U: drive, and point your Matlab workspace to it.
3 points each (max 11 points):
1) RELATIONAL OPERATORS Create a script file called stocks.m, where we will solve the following
problem:
Start by entering a set of comments at the top of your program, such as the following:
% stocks.m A script to determine the result of a trading strategy
% Your Name
% Assignment 4 problem 1
You’ll then want to define the price vector in your script, just as it is written in the problem statement
above. Do this now. Try typing it into your script without a semicolon. Save, then run the script and
verify it looks good. Then you can go back and add a ‘;’ after it so it does not print out anymore when
you run the script.
The problem describes a trading strategy. We want to buy shares when the price is low, and sell when
they are high. In matlab we can do this by using the relational operators on the price vector. For
example, if we type price<20 in the command window, we’ll get a vector of 1’s and 0’s like this:
[1, 1, 0, 0, 0, 1,1,0,0,0]
This is a logical vector, with 1’s indicating it’s “Time to Buy!!” and we can use it to figure out what our
purchase cost is. Let’s first save this by typing in our script:
buy = price<20
Run the script and verify correct output. Then go back and add the semicolon to suppress. Now we can
use the buy vector to help us determine our expenses. For example, we can get a vector of our purchase
costs by typing
purchaseCost = 100*price(buy)
% 100 shares at price whenever price<20
Try entering this in your script, save it, and run it. Do the numbers make sense to you? The total
purchase price can be determined by taking the sum of the purchaseCost vector:
totalCost = sum(purchaseCost)
To make the script output easier to read, we might want to format our output. Matlab’s fprintf
command will help us with this.
fprintf( '1a) the total cost of purchasing stocks is $%6.2f\n', totalCost);
This means, show a message (in quotes). Where the symbol %6.2f is, this is where our variable totalCost
will appear. %6.2f means it will show the number in a field of 6 characters wide, with 2 digits after the
decimal point. Finally, we have to include \n in quotes to make sure we go to a new line on output. This
is a good time to go back and put semicolons (;) after every line to suppress the intermediate output.
Code up the above statements in your script, save it, and try it out by typing stocks at the command line.
Now add your solution for part b), which is very similar to part a)
For c) you can create a vector showing how many shares you bought each day with the expression
shares = 100*buy, and from there with a little work you should be able to find the total shares you own
after 10 days.
For d) the worth of your portfolio at any time would be the number of shares times the current price. So
your portfolio would initially be $19,000. Once you determine the answer to c) you can find your
portfolio worth on the 10th day and then calculate the net gain (or loss).
Before leaving this problem, consider this: How do you know the answer is correct? Can you verify the
answer somehow? Go back and reduce price so there are only 3 days of data in it (just comment the
original out and put in the shorter vector. Your solution should not depend on the size of the vector, and
three is a number you can check with a calculator. Do this now and make sure your matlab code agees.
2) LOGICAL OPERATORS Create a script file called projectile.m, where we will solve the following
problem:
First add a comment block at the top simiilar to what you created for problem 1. This problem involves
selecting portions of a projectile path based on various logical criteria.
To begin, we’ll need to establish the constants A, vo, and g, so put those in at the top of your script.
Next, calculate thit based on the formula given.
To do this problem, we’ll need to create vectors for height and velocity, and since they are based on
time, let’s first create the time vector (call it t), which should range from 0 to thit with about 100 points
total. Add this now, without semicolon, save and run to make sure it works right, then add semicolon
and continue.
Now compute v and h based on the formulas given. To ensure you calculated these right, plot them in
your script now. Create a plot that looks something like this one below.
You can add a legend with the command
legend('height, m','speed, m/s','location','east');
assuming that height was plotted before speed. Add xlabel and title in your script, then run and save
your plot as projPlot.jpg
Now that we have the vectors set up we can begin to figure out the actual problem. We are going to use
find to help us determine the times of interest. For a) we can find what cells in h are bigger than (or
equal to) 15 with the command find( h > 15). Since we’ll need to use these numbers again, lets save
them in another vector, like so:
higher15 = find(h>15)
(As usual, test the new line in your script without the semicolon, then add it to suppress further output.)
What this operation gives us is the cell numbers where the height vector had values >= 15. We want to
know what times those were at. So we can use the higher15 vector to select the corresponding of times
of those h values that were bigger than 15, such as
t_higher15 = t(higher15)
But this gives us a whole vector of times! We can do better than that. To find the first time we can just
feed the first value of higher15 into the t vector. So this would look like
t_higher15_start = t( higher15(1))
% lookup the t for the first found cell# with height > 15
We can find the last time that h was >=15 by just picking out the last value in the higher15 vector. This is
done with the special word “end” which means the last cell in a vector:
t_higher15_end = t( higher15(end))
% lookup the t for the last found cell# with height > 15
That’s it! Now we can print them out with a formated print statement:
fprintf( '2a) the times for h>=15 are from %6.2f to %6.2f\n', t_higher15_start, t_higher15_end);
For b) and c) , you can extend your answer to a using the logical operators & and | as discussed in
lecture.
3) IF and IF-ELSE STATEMENTS (Scalar data) Create a function file called leapYear.m in which we will
solve the following problem:
There are times when the logic of a problem is too complicated to be solved using vector operations.
This is one of them, and therefore we will have to use if statements to solve this problem. The leapyear
calculation will take as input a single year and as output will return a 1 or 0 depending on if a year is a
leapyear or not. We will create this as a function file to make it easier to use in other programs we may
write later.
To begin, write the function header on the very first line of the file:
function extraDay = leapYear( year )
this means the function will take a year parameter and return a value indicating whether year is a leap
year (an extra day must be added to February) or not a leap year (extraDay = 0)
add the usual set of comments to the lines following the function header, explaining how the function
can be used. For example leapYear(1800) should return 0 (not a leap year), while leapYear(2400)
should return 1 ( a leap year).
Note that as a rule, we DO NOT PRINT ANY MESSAGES from inside a function. DON’T use fprintf. That
simply displays a value but doesn’t allow us to do anything useful with it. Only by returning a value such
as extraDay can we take the result of a function and use it in further calculations (for example, in a
calandar program).
This program will rely on our ability to determine whether a year is divisible by a number such as 100 or
4. The mod function in Matlab helps us do that. At the command line, try a few mod statements:
mod(10,5)
mod(16,6)
mod(23,14)
% remainder of 10 divided by 5
% remainder of 16 divided by 6
% remainder of 23 divided by 14
and notice the result it gives. Make sure you verify you understand what it does.
The first part of the solution is to determine if year is divisible by 400. We can do that with the if
statement
if mod( ______, ________) == 0
extraDay = 1;
else
extraDay = 0;
end
% fill in the blanks
This is just a starting point but it provides enough that you can save and test your function. Try typing
leapYear(1600) on the command line and it should come back with ‘1’. However, 1700 should come
back with ‘0’.
In order to extend this solution you’ll need to add additional elseif sections to handle if the prior
conditions were false. In other words, your structure will be of the form
if ______________
% condition 1 for leap year
extraDay = 1;
elseif _______________ % condition 2 = NOT a leap year
extraDay = 0;
elseif _______________ % condition 3 for leap year
extraDay = 1;
else
% ran out of conditions, it’s not a leap year
extraDay = 0;
end
4) Challenge – Create a function file called spring.m that will be used to solve the following problem:
You can solve this function with scalar operations such as the leap year (if statements, etc)
However, it is best in matlab to use a vectorized approach wherever possible, and this problem does
have a reasonably simple vector solution that will do away with any if statements.
So we will therefore assume W is a vector although if you like you can do it with W assumed to be scalar.
The trick for doing a vectorized version is to
a) create a dummy x vector of displacements that has the same size as W. The command
x = zeros( size(W)) will do the trick. It makes x a zero filled array the same size as W.
b) determine (using find and the relational operators) which cells of W will cause a displacement x
less than d, and which cells of W will cause a displacement x that exceeds d. You can then use
those cell values to replace the zeros in the x vector with the appropriate formula for x.
c) When you have the function working, plot the curve x vs W (that is, W on the x-axis, x on the yaxis!) from the command line and save as springPlot.jpg
TURN IN PROCEDURE: zip your A4 folder and upload to the homework uploader link on the webpage.