Homework 3: Iteration

2/12/2015
Homework 3: Iteration
Homework 3: Iteration
Due: Noon on Thursday, February 19.
For this homework, you should use for and while loops wherever possible, and not MATLAB's built­in array functions
or logical indexing.
For each homework assignment, there may be support files that you will need to complete the assignment. These can be
copied to your home directory by using the following command in a Brown CS Terminal window:
cs4_install hw03
There should now be a hw03 folder within your homeworks folder. Using Terminal, you can move into the hw03 folder with
the cd command.
Create a script called cs4hw03.m with answers and comprehensive test cases. Use the following Publish friendly format
to organize your work in cs4hw03.m
%% Question 3.1
% Put comments for any written answers to non-coding questions here.
%%
% *A) Test cases*
assert(isequal(xxx(a,b,c), [1 2 2])); % Put your assert statements here.
...
%%
% *B) Function Listing(s)*
dbtype xxx.m % Where xxx.m is the name of a function you have written.
...
%% Question 3.2
...
_____________________________________________________________
Contents
Question 3.1: Even and odd entries (10)
Question 3.2 (ITM 5.6): Compound Interest (10)
Question 3.3 (ITM 5.8): Dice Scores (10)
Question 3.4: Probability Estimates (15)
Question 3.5 (ITM 5.11): Prime Fibonacci numbers (20)
Question 3.6: N largest unique elements (20)
Question 3.7 (ITM 11.9): Power play (5)
Question 3.8 (ITM 11.11): Stochastic Fractal (10)
Question 3.1: Even and odd entries (10)
Write a function with header [Q] = myTrigOddEven(M) where Q(i,j) = sin(pi/M(i,j)) if i*j is odd
and Q(i,j) = cos(pi/M(i,j)) if i*j is even. You may assume that M is a non­empty, two­dimensional matrix
of doubles. Do not assume M will always be square.
Example Output:
file:///Users/Dan/Desktop/hw03/html/hw03.html
1/8
2/12/2015
Homework 3: Iteration
myTrigOddEven([3 4; 6 7])
ans =
0.8660
0.8660
0.7071
0.9010
Question 3.2 (ITM 5.6): Compound Interest (10)
An interest rate, , on a principle amount , defines a payment amount for the use of the principle over time. Compound
interest is accumulated according to the formula , where is the number of compounding periods (usually
months or years). Write a function with header [periods] = mySavingPlan(P0, i, goal) where periods
is the whole number of periods it will take your total savings account balance to attain goal at i% interest per period.
Assume no additional deposits or withdrawals. Assume is positive.
Use iteration to solve this problem, not a closed­form solution.
Example Output:
mySavingPlan(1000, 0.05, 2000) % Rate of 5 percent
ans =
15
mySavingPlan(1000, 0.07, 2000) % Rate of 7 percent
ans =
11
mySavingPlan(500, 0.07, 2000) % 7 percent with a bigger difference between P_0 and goal
ans =
21
Question 3.3 (ITM 5.8): Dice Scores (10)
Assume you are rolling two six­sided dice, each side having an equal chance of occurring. Write a function with header
file:///Users/Dan/Desktop/hw03/html/hw03.html
2/8
2/12/2015
Homework 3: Iteration
[score] = myDiceScore(), where score is the sum of the values of the two dice thrown, but with the following
extra rule: if the two dice rolls are the same, then another roll is made, and the new sum is added to the running total.
Examples: If the two dice show 3 and 4, then the running total score should be 7. If the two dice show 1 and 1, then the
running total score should be 2 plus the total of another throw. Rolls stop when the dice rolls are different.
Hint: The line result = randi([1 6],2,1) is an accurate simulation of rolling two dice; result is a 2 by 1 matrix.
Testing random outputs is challenging. For now, compare your results with the figure below by placing the following code in
your test file:
rng(0); % set random number generator seed to zero
rolls = zeros(1,100000);
for i = 1:100000
scores(i) = myDiceScore();
end
hist(scores, 25)
xlabel('Score')
ylabel('Number of Occurences')
title('Histogram of Dice Scores')
Question 3.4: Probability Estimates (15)
Create a function [Pest] = myProbAtLeastN(N, trials) that estimates the probability of a score of N or
more during a Dice player's turn using a vector trials of prior score data. When N is a vector, return estimates for each
element of N(i) in the same shape as N.
file:///Users/Dan/Desktop/hw03/html/hw03.html
3/8
2/12/2015
Homework 3: Iteration
Estimate the probability of an event by using the following formula:
Example Output
myProbAtLeastN([1 6 11 16 20], randi([1 20],1,1000000))
ans =
1.0000
0.7506
0.5004
0.2503
0.0499
myProbAtLeastN([1 3 5], [1 2 3 4 5])
ans =
1.0000
0.6000
0.2000
Additional Questions Place your answers and MATLAB calculations to the following questions in cs4hw03.m.
Question 3.4.1 Using scores from 100,000 turns, what is the estimated probability of a player having score of at least 10?
Question 3.4.2 Using scores from 100,000 turns, what is the estimated probability of a player having a score of at least 30?
Question 3.4.3 If you rerun these estimates (i.e. create new scores and re­estimate; do not use rng(0) when you
generate a new set of scores), which estimate is more stable? Why? (Compare the relative error between runs.)
Question 3.5 (ITM 5.11): Prime Fibonacci numbers (20)
Write a function with header [fibPrimes] = myNFibPrimes(N), where fibPrimes is a list of the first N numbers that are both a
Fibonacci number and prime. Assume N is a non­negative integer.
Do not use the recursive implementation of Fibonacci numbers. A function to compute Fibonacci numbers is presented in
ITM Section 6.1. You may use the code freely.
Hints: 1 is not prime. You are welcome to to use the MATLAB isprime function, or write your own function.
Example Output:
myNFibPrimes(3)
ans =
2
3
5
file:///Users/Dan/Desktop/hw03/html/hw03.html
4/8
2/12/2015
Homework 3: Iteration
myNFibPrimes(8)
ans =
Columns 1 through 6
2
3
5
13
89
233
Columns 7 through 8
1597
28657
Question 3.6: N largest unique elements (20)
Write a function with signature [M] = myNMax(A,n) where M is an array consisting of the n largest unique values in
array A. If the number of unique elements in M is less than n, just return all the unique values found. If A is empty, M should
be empty.
Your solution should rely solely on looping and if­statements, and should index elements one at a time.
Do not use any of the built­in Matlab set functions (e.g., unique) to code your solution. Do not use the max function or
any of MATLAB's built­in sorting functions. Do not use logical indexing.
Hints: First, try coding your solution to find the max of A, then adjust your solution to find the n largest unique values, while
assuming A has at least n unique values. Finally, adjust your code to accomodate the case when A has fewer than n unique
values. You will receive partial credit for functional but incomplete solutions, as long as they are documented as such and
have test cases.
Example Ouput:
myNMax([132 Inf 3 3 2], 3)
ans =
Inf
132
3
myNMax([1 2 3; 1 2 3; 9 0 9],7)
ans =
9
3
2
file:///Users/Dan/Desktop/hw03/html/hw03.html
1
0
5/8
2/12/2015
Homework 3: Iteration
Question 3.7 (ITM 11.9): Power play (5)
Write a function with header [] = myPolyPlotter (n,x) that plots the polynomials p_k(x) = x^k for k = 1, ..., n. Make sure your
plot has axis labels, a title, legend, and grid lines. Use doc legend to learn how to control the Location of a legend.
Make your graph matches the following:
myPolyPlotter(5,-1:.01:1)
Question 3.8 (ITM 11.11): Stochastic Fractal (10)
Generate a set of points (x_i, y_i) where x_1 = 0 and y_1 = 0. The points (x_i, y_i) for i = 2, ..., n are created by the following
probabilistic relationships:
With 1% probability:
With 7% probability:
With 7% probability:
file:///Users/Dan/Desktop/hw03/html/hw03.html
6/8
2/12/2015
Homework 3: Iteration
With 85% probability:
Write a function with signature [] = myFern(n) that generates the points (x_i,y_i) for i=1,..., n and plots them using
blue dots.
Hint: Your code will run faster if you generate all the points, and then plot them using a single plot command.
Try your function for n = 1000 and n = 10000. The image generated is called a stochastic fractal. Despite being very easy to
generate, fractals often exhibit a lot of complexity. They have application in both computer graphics and image
compression.
Below is a figure generated by myFern(100).
close all
figure(1)
myFern(100)
___________________________________________________________
file:///Users/Dan/Desktop/hw03/html/hw03.html
7/8
2/12/2015
Homework 3: Iteration
Make sure all the m­files you want to submit are in your Brown CS ~/course/cs004/homeworks/hw03 directory.
Be sure to turn in ALL the files requested and that they are named exactly as specified, including spelling and case. When
you?re ready to submit the files, run
cs4_handin hw03
using a Brown CS account terminal window. The entire contents of your ~/course/cs004/homeworks/hw03
directory will be handed in.
Published with MATLAB® R2014b
file:///Users/Dan/Desktop/hw03/html/hw03.html
8/8