Assignment 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

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).

function [roll] = myMonopolyDice()


r=randi(6,1,2)
roll=sum(r);
while r(1)==r(2)
r=randi(6,1,2)
roll=roll+sum(r);
end
end

5. 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. Note: 1 is not prime.

function [fibPrimes] = myNFibPrimes(N)


i=1;j=1;
while i<=N
a=fibonacci(j);
if isprime(a)
fibPrimes(i)=fibonacci(j)
i=i+1;
end
j=j+1;
end

end

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy