Assignment 4
Assignment 4
Assignment 4
1. Write a function with header [M] = myMax(A) where M is the maximum (largest) value in
A. Do not use the built-in MATLAB function max.
function [M]=myMax(A)
M=0;
[r,c]=size(A);
for i=(1:r)
for j=(1:c)
if A(i,j)>M
M=A(i,j);
end
end
end
end
2. Write a function with header [M] = myNMax(A,N) where M is an array consisting of the N
largest elements of A. You may use MATLAB’s max function. You may also assume that N is
less than the length of M, that A is a one-dimensional array with no duplicate entries,
and that N is a strictly positive integer smaller than the length of A.
function [M]=myNMax(A,N)
for i=1:N
[M(i),I]=max(A);
A(I)= -Inf;
end
end
3. The interest, i, on a principle, P0, is a payment for allowing the bank to use your
money. Compound interest is accumulated according to the formula Pn = (1 + i)Pn-1, where
n is the compounding period, usually in months or years. Write a function with header
[years] = mySavingPlan(P0, i, goal) where years is the number of years it will take P0 to
become goal at i% interest compounded annually.
function [years]=mySavingPlan(P,i,goal)
years=0;
while P<goal
years=years+1;
P=(1+i)*P;
end
end
4. Assume you are rolling two six-sided dice, each side having an equal chance of
occurring. Write a function with header [roll] = myMonopolyDice(), where roll is the sum
of the values of the two dice thrown but with the following extra rule: if the two dice
1
rolls are the same, then another roll is made, and the new sum added to the running total.
If the two dice show 3 and 4, then the running total should be 7. If the two dice show
1 and 1, then the running total 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 (See Figure 5.1).
end