Chapter 6 Solved Problems · Chapter 6: Solved Problems 5 6. Use loops to create a matrix in which...
Transcript of Chapter 6 Solved Problems · Chapter 6: Solved Problems 5 6. Use loops to create a matrix in which...
1
Chapter 6 Solved Problems
1. Evaluate the following expressions without using MATLAB. Check theanswers with MATLAB.(a) (b)
(c) (d)
Solution
>> % Part (a)>> 6*4>32-3ans = 0>> % Part (b)>> y=4*3-7<15/3>-1y = 1>> % Part (c)>> y=2*(3<8/4+2)^2<(-2)y = 0>> % Part (d)>> (5+~0)/3==3-~(10/5-2)ans = 1>>
2 Chapter 6: Solved Problems
2. Given: , , . Evaluate the following expressions withoutusing MATLAB. Check the answers with MATLAB.(a) (b)(c) (d)
Solution
>> d=6d = 6>> e=4e = 4>> f=-2f = -2>> % Part (a)>> y=d+f>=e>d-ey = 0>> % Part (b)>> y=e>d>fy = 1>> % Part (c)>> y=e-d<=d-e==f/fy = 1>> % Part (d)>> y=(d/e*f<f)>-1*(e-d)/fy = 1>>
Chapter 6: Solved Problems 3
3. Given: v = [–2 4 1 0 2 1 2 ] and w = [2 5 0 1 2 –1 3 ]. Evaluate the follow-ing expressions without using MATLAB. Check the answers with MAT-LAB.(a) ~v ==~w (b) w > = v(c) v > ~ –1*w (d) v > –1*w
Solution
>> v=[-2 4 1 0 2 1 2]v = -2 4 1 0 2 1 2>> w=[2 5 0 1 2 -1 3]w = 2 5 0 1 2 -1 3>> % Part (a)>> ~v==~wans = 1 1 0 0 1 1 1>> % Part (b)>> w>=vans = 1 1 0 1 1 0 1>> % Part (c)>> v>~1*wans = 0 1 1 0 1 1 1>> % Part (d)>> v>-1*wans = 0 1 1 1 1 0 1>>
4 Chapter 6: Solved Problems
4. Use the vectors v and w from Problem 3. Use relational operators to create avector u that is made up of the elements of v that are smaller than or equalto the elements of w.
Solution
Command Window:
>> v=[-2 4 1 0 2 1 2];>> w=[2 5 0 1 2 -1 3];>> u=v(v<=w)u = -2 4 0 2 2
5. Evaluate the following expressions without using MATLAB. Check theanswers with MATLAB.(a) 0|7&9&–3 (b) 7>6&~0<=2(c) ~4<5|0>=12/6 (d) – 7<–5<–2&2+3<=15/3
Solution
>> % Part (a)>> 0|7&9&-3ans = 1>> % Part (b)>> 7>6&~0<=2ans = 1>> % Part (c)>> ~4<5|0>=12/6ans = 1>> % Part (d)>> -7<-5<-2&2+3<=15/3ans = 0>>
Chapter 6: Solved Problems 5
6. Use loops to create a matrix in which the value of each element is twotimes its row number minus three times its column number. For example, thevalue of element (2,5) is .
Solution
Script File
for i=1:4 for j=1:6 A(i,j)=2*i-3*j; endendA
Command Window:
A = -1 -4 -7 -10 -13 -16 1 -2 -5 -8 -11 -14 3 0 -3 -6 -9 -12 5 2 -1 -4 -7 -10
7. Write a program that generates a vector with 30 random integers between–20 and 20 and then finds the sum of the all the elements that are divisibleby 3.
Solution
Script File:
v=randi([-20 20],1,30)n=length(v);S=0;for i=1:n if rem(v(i),3)==0 S=S+v(i); endendS
6 Chapter 6: Solved Problems
Command Window:
v = Columns 1 through 12 10 -10 0 8 16 19 2 -15 -14 -
10 14 -10 Columns 13 through 24 13 -11 18 -6 -12 -10 5 -1 -6
14 3 2 Columns 25 through 30 17 -9 11 10 -5 3S = -24
8. Write a program that asks the user to input a vector of integers of arbitrarylength. Then, using a for loop the program examine each element of the vec-tor. If the element is positive its value is doubled. If the element is negativeits value is tripled. The program displays the vector that was entered and themodified vector. Execute the program and when the program ask the user toinput a vector type randi([-10 20],1,19). This creates a 19-elementvector with random integers between –10 and 20.
Solution
Script File:v=randi([-10 20],1, 19)n=length(v);for i=1:n if v(i) > 0 v(i)=2*v(i); end if v(i) < 0 v(i)= 3*v(i); endendvNew=v
Command Window:
v = Columns 1 through 15
Chapter 6: Solved Problems 7
-8 -9 6 14 18 -6 7 4 -100 -5 14 -1 6 -5
Columns 16 through 19 8 -2 10 11vNew = Columns 1 through 15 -24 -27 12 28 36 -18 14 8 -30
0 -15 28 -3 12 -15 Columns 16 through 19 16 -6 20 22
9. Write a program that asks the user to input a vector of integers of arbitrarylength. Then, using a for loop the program eliminates all the negative ele-ments. The program displays the vector that was entered and the modifiedvector, and a message that says how many elements were eliminated. Exe-cute the program and when the program ask the user to input a vector typerandi([-15 20],1,25). This creates a 25-element vector with randomintegers between –15 and 20.
Solution
Script File:
v=randi([-15 20],1, 25)n=length(v);j=0;for i=1:n if v(i) >= 0 j=j+1; vNew(j)=v(i); endendelim=n-j;vNewfprintf('%.0f elements were eliminated.\n',elim)
Command Window:
v = Columns 1 through 13
8 Chapter 6: Solved Problems
17 6 7 15 13 5 -9 -7 16 -14 2 -9 20
Columns 14 through 25 10 3 1 -13 9 -14 -13 3 -12
14 14 11vNew = Columns 1 through 13 17 6 7 15 13 5 16 2 20
10 3 1 9 Columns 14 through 17 3 14 14 118 elements were eliminated.
10. The daily high temperature (°F) in New York City and Denver, Coloradoduring the month of January 2014 is given in the vectors below (data fromthe U.S. National Oceanic and Atmospheric Administration).NYC = [33 33 18 29 40 55 19 22 32 37 58 54 51 52 45 41 45 39 3645 33 18 19 19 28 34 44 21 23 30 39]DEN = [39 48 61 39 14 37 43 38 46 39 55 46 46 39 54 45 52 52 6245 62 40 25 57 60 57 20 32 50 48 28]where the elements in the vectors are in the order of the days in the month.Write a program in a script file that determines and displays the followinginformation:(a) The average temperature for the month in each city (rounded to the
nearest degree).(b) The number of days that the temperature was above the average in each
city.(c) The number of days that the temperature in Denver was higher than the
temperature in New York.
Solution
Script File:
clear, clcNYC = [33 33 18 29 40 55 19 22 32 37 58 54 51 52 45 41 45 ... 39 36 45 33 18 19 19 28 34 44 21 23 30 39];DEN = [39 48 61 39 14 37 43 38 46 39 55 46 46 39 54 45 52 ... 52 62 45 62 40 25 57 60 57 20 32 50 48
Chapter 6: Solved Problems 9
28];%Part (a)NYCav=round(mean(NYC));DENav=round(mean(DEN));fprintf('The averager temperature in New York City is: % g F.\n',NYCav)fprintf('The averager temperature in Denver is: % g F.\n',DENav)%Part (b)nNYC=sum(NYC>NYCav);nDEN=sum(DEN>DENav);fprintf('During % g days the temperature in New York City was above the average.\n',nNYC)fprintf('During % g days the temperature in Denver was above the average.\n',nDEN)%Part (c)DENhNYC=sum(DEN>NYC);fprintf('During % g days the temperature in Denver was
higher than in New York City.\n',DENhNYC)
Command Window:
The averager temperature in New York City is: 35 F.The averager temperature in Denver is: 44 F.During 15 days the temperature in New York City was
above the average.During 18 days the temperature in Denver was above the
average.During 22 days the temperature in Denver was higher than
in New York City.
10 Chapter 6: Solved Problems
11. The Pascal’s triangle can be displayed as elements in alower-triangular matrix as shown on the right. Write aMATLAB program that creates a matrix that dis-plays n rows of Pascal’s triangle. Use the program to create4 and 7 rows Pascal’s triangles. (One way to calculate thevalue of the elements in the lower portion of the matrix is
.)
Solution
Script File:
n=6;pt=zeros(n);for i=1:n for j=1:i pt(i,j)=factorial(i-1)/(factorial(j-1)*factorial(i-j)); endendpt
Command Window:
pt = 1 0 0 0 0 0 1 1 0 0 0 0 1 2 1 0 0 0 1 3 3 1 0 0 1 4 6 4 1 0 1 5 10 10 5 1
1 0 0 0 0 01 1 0 0 0 01 2 1 0 0 01 3 3 1 0 01 4 6 4 1 01 5 10 10 5 1
Chapter 6: Solved Problems 11
12. Tribonacci numbers are the numbers in a sequence in which the first threeelements are 0, 1, and 1, and the value of each subsequent element is the sumof the previous three elements:
0, 1, 1, 2, 4, 7, 13, 24, ...Write a MATLAB program in a script file that determines and displays thefirst 25 Fribonacci numbers.
Solution
Script File:
F(1)=0;F(2)=1;F(3)=1;for i=4:25 F(i)=sum(F([i-3:i-1]));endF
Command Window:
F = Columns 1 through 6 0 1 1 2 4
7 Columns 7 through 12 13 24 44 81 149
274 Columns 13 through 18 504 927 1705 3136 5768
10609 Columns 19 through 24 19513 35890 66012 121415
223317 410744 Column 25 755476
12 Chapter 6: Solved Problems
13. The reciprocal Fibonacci constant is defined by the infinite sum:
where are the Fibonacci numbers 1, 1, 2, 3, 5, 8, 13, ... . Each element inthis sequence of numbers is the sum of the previous two. Start by setting thefirst two elements equal to 1, then . Write a MATLAB pro-gram in a script file that calculates for a given n. Execute the program for
and 100.
Solution
Script File:n=50;F(1)=1;F(2)=1;for i=3:n F(i)=F(i-2)+F(i-1);endxi=sum(1./F)
Command Window:
xi = 3.359885666243178
14. The value of π can be estimated from:
Write a program (using a loop) that determines π for a given n. Run the pro-gram with n = 10, n = 100, and n = 1000. Compare the result with pi. (Useformat long.)
Solution
Script File:format longn=input('Enter a value for n ');S=0;for i=0:n S=S+(-1)^i/(2*i+1)^3;end
ψ
ψn 1=
∞
=
Fn
ψn 10 50, ,=
n 0=
∞
Chapter 6: Solved Problems 13
ESpi=(32*S)^(1/3)
Command Window:
Enter a value for n 10ESpi = 3.141642788603785>> ed6_HW6_14Enter a value for n 100ESpi = 3.141592719141050>> ed6_HW6_14Enter a value for n 1000ESpi = 3.141592653657139
15. The value of can be estimated from the expression:
Write a MATLAB program in a script file that determine for any numberof terms. The program asks the user to enter the number of terms, and thencalculates the corresponding value of . Execute the program with 5, 10,and 40 terms. Compare the result with pi. (Use format long.)
Solution
Script File:
format longn=5;S2=0;S=1;for i=1:n S2=sqrt(2+S2); S=S*S2/2;endpiEst=2/S
Command Window:
π
π
π
14 Chapter 6: Solved Problems
piEst = 3.140331156954753
With n=10:
piEst = 3.141591421511200
With n=40:
piEst = 3.141592653589794
16. Write a program that (a) generates a vector with 20 random integer elementswith integers between 10 and 30, (b) replaces all the elements that are noteven integers with random integers between 10 and 30, (c) repeats (b) untilall the elements are even integers. The program should also count how manytimes (b) is repeated before all the elements are even integers. When done,the program displays the vector and a statement that states how many itera-tions were needed for generating the vector.
Solution
Script File:vInitial=randi([10 30],1, 20)for i=1:30 c=0; for j=1:20 if rem(vInitial(j),2) ~=0 vInitial(j)=randi([10 30]); c=1; end end if c ==0 break endendvFinal=vInitialfprintf('%.0f iterations were done.\n',i-1)
Command Window:
Chapter 6: Solved Problems 15
vInitial = 27 12 22 17 26 20 20 28 17
19 30 10 30 13 24 22 24 17 23 27
vFinal = 10 12 22 28 26 20 20 28 30
16 30 10 30 14 24 22 24 18 12 12
4 iterations were done.
17. A vector is given by x = [9 –1.5 13.4 13.3 –2.1 4.6 1.1 5 –6.1 10 0.2].Using conditional statements and loops, write a program that rearrangesthe elements of x in order from the smallest to the largest. Do not use MAT-LAB’s built-in function sort.
Solution
Script file:
clear, clcx=[9 -1.5 13.4 13.3 -2.1 4.6 1.1 5 -6.1 10 0.2]n=length(x);for i=1:n-1 for j=i+1:n if x(j)<x(i) t=x(i); x(i)=x(j); x(j)=t; end endendx
Command Window:
x = 9.0000 -1.5000 13.4000 13.3000 -2.1000
4.6000 1.1000 5.0000 -6.1000 10.00000.2000
x = -6.1000 -2.1000 -1.5000 0.2000 1.1000
16 Chapter 6: Solved Problems
4.6000 5.0000 9.0000 10.0000 13.300013.4000
>>
18. The Pythagorean theorem states that . Write a MATLAB pro-gram in a script file that finds all the combinations of triples a, b, and c thatare positive integers all smaller or equal to 50 that satisfy the Pythagoreantheorem. Display the results in a three-column table in which every row cor-responds to one triple. The first three rows of the table are:
3 4 55 12 136 8 10
Solution
Script file:clear, clcid=1;for k=1:50for j=k+1:50for i=j+1:50if i^2==k^2+j^2a(id)=k;b(id)=j;c(id)=i;id=id+1;endendendendtable=[a' b' c']
Command Window:
table = 3 4 5 5 12 13 6 8 10 7 24 25 8 15 17 9 12 15 9 40 41
a2 b2+ c2=
Chapter 6: Solved Problems 17
10 24 26 12 16 20 12 35 37 14 48 50 15 20 25 15 36 39 16 30 34 18 24 30 20 21 29 21 28 35 24 32 40 27 36 45 30 40 50>>
19. Write a MATLAB program in a script file that finds and displays all thenumbers between 100 and 999 whose product of digits is 6 times the sum ofthe digits. (e.g. 347 since ). Use a for loop in the pro-gram. The loop should start from 100 and end at 999.
Solution
Script File:
for n=100:999 h=fix(n/100); d=fix((n-100*h)/10); s=n-h*100-d*10; mul=h*d*s; add=6*(h+d+s); if mul == add n endend
Command Window:
n =
18 Chapter 6: Solved Problems
268n = 286n = 347n = 374n = 437n = 473n = 628n = 682n = 734n = 743n = 826n = 862
20. A safe prime is a prime number that can be written in the form where p isalso a prime number. For example, 47 is a safe prime since and 23is also a prime number. Write a computer program that finds and displays all thesafe primes between 1 and 1000. Do not use MATLAB’s built-in functionisprime.
Solution
Script file:
clear, clck=1;for n=1:500; nispr=1; nsafeisPrime=0; for i=2:fix(n/2) if rem(n,i)==0 nispr=0;
Chapter 6: Solved Problems 19
break end end if nispr==1 nsafe=2*n+1; nsafeisPrime=1; for j=2:fix(nsafe/2) if rem(nsafe,j)==0 nsafeisPrime=0; break end end end if nsafeisPrime==1 SafePrimeNum(k)=nsafe; k=k+1; end endSafePrimeNum
Command Window:
SafePrimeNum = Columns 1 through 7 3 5 7 11 23 47 59 Columns 8 through 14 83 107 167 179 227 263 347 Columns 15 through 21 359 383 467 479 503 563 587 Columns 22 through 26 719 839 863 887 983
20 Chapter 6: Solved Problems
21. Sexy primes are two prime numbers that the difference between them is 6. Forexample, 23 and 29 are sexy primes since . Write a computer pro-gram that finds all the sexy primes between 1 and 300. The numbers should bedisplayed in a two-column matrix where each row display one pair. Do not useMATLAB’s built-in function isprime.
Solution
Script file:
clear, clck=1;for n=1:300; nispr=1; nSexyeisPrime=0; for i=2:fix(n/2) if rem(n,i)==0 nispr=0; break end end if nispr==1 nsexy=n+6; nSexyeisPrime=1; for j=2:fix(nsexy/2) if rem(nsexy,j)==0 nSexyeisPrime=0; break end end end if nSexyeisPrime==1 SexyPrimeNum(k,1)=n; SexyPrimeNum(k,2)=nsexy; k=k+1; end endSexyPrimeNum
Command Window:
Chapter 6: Solved Problems 21
SexyPrimeNum = 1 7 5 11 7 13 11 17 13 19 17 23 23 29 31 37 37 43 41 47 47 53 53 59 61 67 67 73 73 79 83 89 97 103 101 107 103 109 107 113 131 137 151 157 157 163 167 173 173 179 191 197 193 199 223 229 227 233 233 239 251 257 257 263 263 269 271 277 277 283>>
22 Chapter 6: Solved Problems
22. A Mersenne prime is a prime number that is equal to , where n is an inte-
ger. For example, 31 is a Mersenne prime since . Write a computerprogram that finds all the Mersenne primes between 1 and 10,000. Do not useMATLAB’s built-in function isprime.
Solution
Script file:
clear, clck=1;for N=3:10000; nispr=1; for i=2:fix(N/2) if rem(N,i)==0 nispr=0; break end end if nispr==1 n=ceil(log(N)/log(2)); if N == 2^n-1 MersennePrimes(k)=N; k=k+1; end endendMersennePrimes
Command Window:
MersennePrimes = 3 7 31 127 8191
Chapter 6: Solved Problems 23
23. A perfect number is a positive integer that is equal to the sum of its positive divi-sors except the number itself. The first two perfect numbers are 6 and 28 since
and . Write a computer program that finds thefirst four perfect numbers.
Solution
Script file:
clear, clcj=1;for N=2:10000 clear div div(1)=1; k=2; for i=2:fix(N/2) if rem(N,i)==0 div(k)=i; k=k+1; end end if sum(div)==N PerfectN(j)=N; j=j+1; endendPerfectN
Command Window:
PerfectN = 6 28 496 8128>>
24 Chapter 6: Solved Problems
24. A list of exam scores (S) (in percent out of 100%) is given: 72, 81, 44, 68, 90,53, 80, 75, 74, 65, 50, 92, 85, 69, 41, 73, 70, 86, 61, 65, 79, 94, 69.Write a computer program that calculates the average (Av) and standarddeviation (Sd) of the scores, which are rounded to the nearest integer. Then,the program determines the letter grade of each of the scores according tothe following scheme:
The program displays the values of Av and Sd followed by a list that showsthe scores and the corresponding letter grade (e.g. 72% Letter grade C).
Solution
Script file:
clear,clcG=[72 81 44 68 90 53 80 75 74 65 50 92 85 69 41 73 70 86 61 65 79 94 69];Av=round(mean(G));S=round(std(G));fprintf('Average grade is %3.0f%%. Standard deviation is %3.0f%%.\n',Av,S)disp(' ')n=length(G);for i=1:n if G(i) > Av+1.3*S fprintf('%3i%% Letter grade A\n',G(i)) elseif G(i) > Av+0.5*S & G(i) < Av+1.3*S fprintf('%3i%% Letter grade B\n',G(i)) elseif G(i) > Av-0.5*S & G(i) < Av+0.5*S fprintf('%3i%% Letter grade C\n',G(i)) elseif G(i) > Av-1.3*S & G(i) < Av-0.5*S fprintf('%3i%% Letter grade D\n',G(i)) elseif G(i) < Av-1.3*S fprintf('%3i%% Letter grade F\n',G(i)) end
Score (%)
Letter grade A BScore (%)
Letter grade C DScore (%)
Letter grade F
Chapter 6: Solved Problems 25
end
Command Window:
Average grade is 71%. Standard deviation is 14%. 72% Letter grade C 81% Letter grade B 44% Letter grade F 68% Letter grade C 90% Letter grade A 53% Letter grade D 80% Letter grade B 75% Letter grade C 74% Letter grade C 65% Letter grade C 50% Letter grade F 92% Letter grade A 85% Letter grade B 69% Letter grade C 41% Letter grade F 73% Letter grade C 70% Letter grade C 86% Letter grade B 61% Letter grade D 65% Letter grade C 79% Letter grade B 94% Letter grade A 69% Letter grade C>>
26 Chapter 6: Solved Problems
25. The Taylor series expansion for ax is:
Write a MATLAB program that determines ax using the Taylor seriesexpansion. The program asks the user to type a value for x. Use a loop foradding the terms of the Taylor series. If cn is the nth term in the series, thenthe sum Sn of the n terms is . In each pass calculate the esti-
mated error E given by . Stop adding terms when .
The program displays the value of ax. Use the program to calculate:(a) 23.5 (b) 6.31.7 Compare the values with those obtained by using a calculator.
Solution
Script File:a=input('Enter a value for a ');x=input('Enter a value for x '); S=1;for n=1:30 cn=log(a)^n/factorial(n)*x^n; Sn=S+cn; if abs((Sn-S)/S)<0.000001 S=Sn; break end S=Sn;endS
Command Window:
Enter a value for a 2Enter a value for x 3.5S = 11.313707964994668
Calculator value: 11.3137085
Enter a value for a 6.3Enter a value for x 1.7
n 0=
∞
Chapter 6: Solved Problems 27
S = 22.849612550742957
Calculator value: 22.84961748
26. Write a MATLAB program in a script file that finds a positive integer n suchthat the sum of all the integers is a number between 100and 1000 whose three digits are identical. As output, the program displaysthe integer n and the corresponding sum.
Solution
Script File:
for n=1:100 Sm=sum(1:n); if Sm >= 100 & Sm <= 1000 h=fix(Sm/100); d=fix((Sm-100*h)/10); s=Sm-h*100-d*10; if h == d & h == s n Sm break end endend
Command Window:
n = 36Sm = 666
1 2 3 … n+ + + +
28 Chapter 6: Solved Problems
27. The following are formulas for calculating the Training Heart Rate (THR):
where MHR is the maximum heart rate given by (https://en.wikipedia.org/wiki/Heart_rate):
For male: , for female: ,
RHR is the resting heart rate, and INTEN the fitness level (0.55 for low, 0.65for medium, and 0.8 for high fitness). Write a program in a script file thatdetermines the THR. The program asks users to enter their gender (male orfemale), age (number), resting heart rate (number), and fitness level (low,medium, or high). The program then displays the training heart rate(rounded to the nearest integer). Use the program for determining the train-ing heart rate for the following two individuals:(a) A 19-year-old male, resting heart rate of 64, and medium fitness level. (b) A 20-year-old female, resting heart rate of 63, and high fitness level.
Solution
Script File:G=input('Please enter gender (Male or Female): ','s');Age=input('Enter age: ');Rhr=input('Enter resting heart rate: ');Int=input('Enter fitness level (low, medium, or high): ','s');switch Int case 'low' Intn=0.55; case 'medium' Intn=0.65; case 'high' Intn=0.8;endswitch G case 'Male' Mhr=203.7/(1+exp(0.033*(Age-104.3))); case 'Female' Mhr=190.2/(1+exp(0.0453*(Age-107.5)));endTHR=round((Mhr-Rhr)*Intn+Rhr)
Command Window:(a)Please enter gender (Male or Female): Male
Chapter 6: Solved Problems 29
Enter age: 19Enter resting heart rate: 64Enter fitness level (low, medium, or high): mediumTHR = 147
(b)Please enter gender (Male or Female): FemaleEnter age: 20Enter resting heart rate: 63Enter fitness level (low, medium, or high): highTHR = 162
28. Body Mass Index (BMI) is a measure of obesity. In standard units, it is cal-culated by the formula
where W is weight in pounds, and H is height in inches. The obesity classifi-cation is:
Write a program in a script file that calculates the BMI of a person. The pro-gram asks the person to enter his or her weight (lb) and height (in.). Theprogram displays the result in a sentence that reads: “Your BMI value isXXX, which classifies you as SSSS,” where XXX is the BMI value roundedto the nearest tenth, and SSSS is the corresponding classification. Use theprogram for determining the obesity of the following two individuals:(a) A person 6 ft 2 in. tall with a weight of 180 lb. (b) A person 5 ft 1 in. tall with a weight of 150 lb.
Solution
Script file:
BMI Classification
Below 18.5 Underweight
18.5 to 24.9 Normal
25 to 29.9 Overweight
30 and above Obese
30 Chapter 6: Solved Problems
clear, clcW=input('Please input your weight in lb: ');h=input('Please input your height in in.: ');BMI=703*W/h^2;if BMI<18.5fprintf('\nYour BMI value is %.1f, which classifies you as underweight\n\n',BMI)elseif BMI<25fprintf('\nYour BMI value is %.1f, which classifies you as normal\n\n',BMI)elseif BMI<30fprintf('\nYour BMI value is %.1f, which classifies you as overweight\n\n',BMI)elsefprintf('\nYour BMI value is %.1f, which classifies you as obese\n\n',BMI)end
Command Window:
Please input your weight in lb: 180Please input your height in in.: 74
Your BMI value is 23.1, which classifies you as normal
Please input your weight in lb: 150Please input your height in in.: 61
Your BMI value is 28.3, which classifies you as overweight
>>
Chapter 6: Solved Problems 31
29. Write a program in a script file that calculates the cost of renting a caraccording to the following price schedule:
The program asks the user to enter the type of car (Sedan or SUV), thenumber of days, and the number of miles driven. The program then displaysthe cost (rounded to cents) for the rent. Run the program three times for thefollowing cases:(a) Sedan, 10 days, 769 miles. (b) SUV, 32 days, 4,056 miles. (c) Sedan, 3 days, 511 miles.
Solution
Script file:
clear, clcT=input('Enter the type of car (Sedan, or SUV) ','s');D=input('Enter the number of days ');M=input('Enter the number of miles '); switch T case 'Sedan' if D <= 6 if M <= D*80 cost=79*D; else cost=79*D+(M-D*80)*0.69; end elseif D <= 29 if M <= D*100 cost=69*D; else cost=69*D+(M-D*100)*0.59; end
Duration of rentSedan SUV
Dailyrate
Freemiles
(per day)
Cost of Additional mile
Dailyrate
Freemiles
(per day)
Cost of Additional mile
1-6 days $79 80 $0.69 $84 80 $0.74
7-29 days $69 100 $0.59 $74 100 $0.64
30 or more days $59 120 $0.49 $64 120 $0.54
32 Chapter 6: Solved Problems
else if M <= D*120 cost=59*D; else cost=59*D+(M-D*120)*0.49; end end case 'SUV' if D <= 6 if M <= D*80 cost=84*D; else cost=84*D+(M-D*80)*0.74 end elseif D <= 29 if M <= D*100 cost=74*D; else cost=74*D+(M-D*100)*0.64; end else if M <= D*120 cost=64*D; else cost=64*D+(M-D*120)*0.54 end endendfprintf('The cost of the rent is $%5.2f\n',cost)
Command Window:
Enter the type of car (Sedan, or SUV) SedanEnter the number of days 10Enter the number of miles 769The cost of the rent is $690.00>>Enter the type of car (Sedan, or SUV) SUVEnter the number of days 32
Chapter 6: Solved Problems 33
Enter the number of miles 4056The cost of the rent is $2164.64 >>Enter the type of car (Sedan, or SUV) SedanEnter the number of days 3Enter the number of miles 511The cost of the rent is $423.99>>
34 Chapter 6: Solved Problems
30. Write a program that determines the change given back to a customer in aself-service checkout machine of a supermarket for purchases of up to $50.The program generates a random number between 0.01 and 50.00 and dis-plays the number as the amount to be paid. The program then asks the userto enter payment, which can be one $1 bill, one $5 bill, one $10 bill, one $20bill, or one $50 bill. If the payment is less than the amount to be paid, anerror message is displayed. If the payment is sufficient, the program calcu-lates the change and lists the bills and/or the coins that make up the change,which has to be composed of the least number each of bills and coins. Forexample, if the amount to be paid is $2.33 and a $10 bill is entered as pay-ment, then the change is one $5 bill, two $1 bills, two quarters, one dime,one nickel, and two pennies. Execute the program three times.
Solution
Script file:
clear, clcAmToPy=randi(5000)/100;fprintf('The amount to be paid is: $%5.2f\n',AmToPy)Cash=input('Please enter payment in dollars (1, 5, 10, 20 or 50) ');if Cash<AmToPy disp('Insufficient payment')else R=[0 0 0 0 0 0 0 0];BilCoin=[2000 1000 500 100 25 10 5 1];C=round((Cash-AmToPy)*100);for i=1:8 if C>=BilCoin(i) Nunit=round(floor(C/BilCoin(i))); R(i)=Nunit; C=C-Nunit*BilCoin(i); endenddisp('The change is:')fprintf('%2.0f $20 bills\n',R(1))fprintf('%2.0f $10 bills\n',R(2))fprintf('%2.0f $5 bills\n',R(3))fprintf('%2.0f $1 bills\n',R(4))fprintf('%2.0f quarters\n',R(5)) fprintf('%2.0f dimes\n',R(6))
Chapter 6: Solved Problems 35
fprintf('%2.0f nickels\n',R(7))fprintf('%2.0f cents\n',R(8))end
Command Window:
The amount to be paid is: $13.93Please enter payment in dollars (1, 5, 10, 20 or 50) 20The change is: 0 $20 bills 0 $10 bills 1 $5 bills 1 $1 bills 0 quarters 0 dimes 1 nickels 2 cents
The amount to be paid is: $27.35Please enter payment in dollars (1, 5, 10, 20 or 50) 50The change is: 1 $20 bills 0 $10 bills 0 $5 bills 2 $1 bills 2 quarters 1 dimes 1 nickels 0 cents
The amount to be paid is: $40.02Please enter payment in dollars (1, 5, 10, 20 or 50) 50The change is: 0 $20 bills 0 $10 bills 1 $5 bills 4 $1 bills 3 quarters 2 dimes 0 nickels 3 cents>>
36 Chapter 6: Solved Problems
31. The concentration of a drug in the body can be modeled by the equation:
where is the dosage administered (mg), is the volume of distribution(L), is the absorption rate constant (h–1), is the elimination rate con-stant (h–1), and t is the time (h) since the drug was administered. For a cer-tain drug, the following quantities are given: mg, L,
h–1, and h–1.(a) A single dose is administered at . Calculate and plot versus t
for 10 hours.(b) A first dose is administered at , and subsequently four more doses
are administered at intervals of 4 hours (i.e., at ). Calcu-late and plot versus t for 24 hours.
Solution
Part (a)Script file:clear, clct=0:0.1:10;n=length(t);DG=150; Vd=50;C=DG/Vd;ke=0.4; ka=1.6;K=ka/(ka-ke);Con=C*K;Cp=Con*(exp(-ke*t)-exp(-ka*t));plot(t,Cp)xlabel('Time (hr)')ylabel('Drug Concentration (mg/L)')
CP
DG Vd
ka ke
DG 150= Vd 50=ka 1.6= ke 0.4=
t 0= CP
t 0=t 4 8 12 16, , ,=
CP
Chapter 6: Solved Problems 37
Figure:
Part (b)Script file:clear, clct=0:0.2:24;n=length(t);DG=150; Vd=50;%C=1.5*100/50;C=DG/Vd;ke=0.4; ka=1.6;K=ka/(ka-ke);Con=C*K;for i=1:n Cp(i)=Con*(exp(-ke*t(i))-exp(-ka*t(i))); if t(i)>4 Cp(i)=Cp(i)+Con*(exp(-ke*(t(i)-4))-exp(-ka*(t(i)-4))); end if t(i)>8 Cp(i)=Cp(i)+Con*(exp(-ke*(t(i)-8))-exp(-ka*(t(i)-8))); end if t(i)>12 Cp(i)=Cp(i)+Con*(exp(-ke*(t(i)-12))-exp(-
38 Chapter 6: Solved Problems
ka*(t(i)-12))); end if t(i)>16 Cp(i)=Cp(i)+Con*(exp(-ke*(t(i)-16))-exp(-ka*(t(i)-16))); endendplot(t,Cp)xlabel('Time (hr)')ylabel('Drug Concentration (mg/L)')
Figure:
Chapter 6: Solved Problems 39
32. One numerical method for calculating the cubic root of a number, is Hal-ley’s method. The solution process starts by choosing a value as a first esti-mate of the solution. Using this value, a second, more accurate value is
calculated with, which is then used for calculating athird, still more accurate value , and so on. The general equation for calculat-
ing the value of from the value of is .Write a MATLAB program that calculates the cubic root of a number. In theprogram use for the first estimate of the solution. Then, by using thegeneral equation in a loop, calculate new, more accurate values. Stop the looping
when the estimated relative error E defined by is smaller than
0.00001. Use the program to calculate:
(a) (b) (c)
SolutionScript File:
P=input('Enter a number for calculating its cubic root: ');xi=P*(P^3+2*P)/(2*P^3+P);for n=1:30 xip1=xi*(xi^3+2*P)/(2*xi^3+P); if abs((xip1-xi)/xi)<0.00001 QRP=xip1; break end xi=xip1;endfprintf ('the qubic root of %g is %g\n',P,QRP)
Command Window:
Enter a number for calculating its cubic root: 800the qubic root of 800 is 9.28318
Enter a number for calculating its cubic root: 59071the qubic root of 59071 is 38.9456
Enter a number for calculating its cubic root: -31.55the qubic root of -31.55 is -3.15985
P3
x1
x2
x3
xi 1+ xi
x1 P=
8003 590713
40 Chapter 6: Solved Problems
33. Write a program in a script file that converts a measure of area given in unitsof either m2, cm2, in2, ft2, yd2, or acre to the equivalent quantity in differentunits specified by the user. The program asks the user to enter a numericalvalue for the size of an area, its current units, and the desired new units. Theoutput is the size of the area in the new units. Use the program to:(a) Convert 55 in2 to cm2. (b) Convert 2400 ft2 to m2.(c) Convert 300 cm2 to yd2.
Solution
Script file:
clear, clcAin=input('Enter the value of the area to be converted: ');AinUnits=input('Enter the current units (sqm, sqcm, sqin, sqft or sqyd): ','s');AoutUnits=input('Enter the new units (sqm, sqcm, sqin, sqft or sqyd): ','s');error=0;switch AinUnitscase 'sqm' Asqcm=Ain*1E4;case 'sqcm' Asqcm=Ain;case 'sqin' Asqcm=Ain*2.54^2;case 'sqft' Asqcm=Ain*(2.54*12)^2;case 'sqyd' Asqcm=Ain*(3*2.54*12)^2;otherwise error=1;endswitch AoutUnitscase 'sqm' Aout=Asqcm*1E-4;case 'sqcm' Aout=Asqcm;case 'sqin' Aout=Asqcm/2.54^2;
Chapter 6: Solved Problems 41
case 'sqft' Aout=Asqcm/(2.54*12)^2;case 'sqyd' Aout=Asqcm/(3*2.54*12)^2;otherwise error=1;endif error disp('ERROR current or new units are typed incorrectly.')else fprintf('A= %g %s\n',Aout,AoutUnits)end
Command Window:
Enter the value of the area to be converted: 55Enter the current units (sqm, sqcm, sqin, sqft or sqyd):
sqinEnter the new units (sqm, sqcm, sqin, sqft or sqyd):
sqcmA= 354.838 sqcm>> Enter the value of the area to be converted: 2400Enter the current units (sqm, sqcm, sqin, sqft or sqyd):
sqftEnter the new units (sqm, sqcm, sqin, sqft or sqyd): sqmA= 222.967 sqm>> Enter the value of the area to be converted: 300Enter the current units (sqm, sqcm, sqin, sqft or sqyd):
sqcmEnter the new units (sqm, sqcm, sqin, sqft or sqyd):
sqydA= 0.0358797 sqyd>>
42 Chapter 6: Solved Problems
34. In a one-dimensional random walk, the position x of a walker is computedby:
where s is a random number. Write a program that calculates the number ofsteps required for the walker to reach a boundary . Use MATLAB’sbuilt-in function randn(1,1) to calculate s. Run the program 100 times(by using a loop) and calculate the average number of steps when .
Solution
Script File:
clear, clcfor j=1:100x=0; for i=1:1000 x=x+randn(1,1); if abs(x)>10 break end end if i==1000 disp('ERROR: Boundary was not reached in 1000 steps') end steps(j)=i;endAveNumSteps=mean(steps)
Command Window:
AveNumSteps = 123.7700>>
xj xj s+=
B 10=
Chapter 6: Solved Problems 43
35. The Sierpinski triangle can be implemented in MATLAB by plotting pointsiteratively according to one of the following three rules that are selected ran-domly with equal probability.Rule 1: ,
Rule 2: ,
Rule 3: ,
Write a program in a script file that calculates the x and y vectors and thenplots y versus x as individual points (use plot(x,y,‘^’)). Start with
and . Run the program four times with 10, 100, 1,000, and10,000 iterations.
Solution
Script file:
clear, clcx(1)=0; y(1)=0;for i=2:10000 n=randi(3); if n==1 x(i)=0.5*x(i-1); y(i)=0.5*y(i-1); elseif n==2 x(i)=0.5*x(i-1)+0.25; y(i)=0.5*y(i-1)+sqrt(3)/4; elseif n==3 x(i)=0.5*x(i-1)+0.5; y(i)=0.5*y(i-1); endend plot(x,y,'^') axis equal
xn 1+ 0.5xn= yn 1+ 0.5yn=
xn 1+ 0.5xn 0.25+=
xn 1+ 0.5xn 0.5+= yn 1+ 0.5yn=
x1 0= y1 0=
44 Chapter 6: Solved Problems
Figure 10 iterations:
Figure 100 iterations:
Figure 1000 iterations:
Chapter 6: Solved Problems 45
Figure 10,000 iterations:
46 Chapter 6: Solved Problems
36. The roots of a cubic equation can be calculatedusing the following procedure:Set: , , and .
Calculate: ,
where and .If the equation has complex roots.If all roots are real and at least two are equal. The roots are given by:
, , and .If all roots are real and are given by:
, , and
, where .Write a MATLAB program that determines the real roots of a cubic equa-tion. As input the program asks the user to enter the values of a3, a2, a1, anda0 as a vector. The program then calculates the value of D. If the equationshas complex roots the message “The equation has complex roots” is dis-played. Otherwise the real roots are calculated and displayed. Use the pro-gram to solve the following equations:
(a) (b)
(c)
Solution
Script File:
v=input('Enter the values of a3, a2, a1, and a0 as a vector: ');a=v(2)/v(1); b=v(3)/v(1); c=v(4)/v(1);Q=(3*b-a^2)/9;R=(9*a*b-27*c-2*a^3)/54;D=Q^3+R^2;if abs(D)<0.01 D=0;endif D > 0 disp('The equation has complex roots.')elseif D ==0 S=nthroot(R,3); x1=2*S-a/3; x2=-S-a/3;
Chapter 6: Solved Problems 47
x3=x2; fprintf('The roots are: %g , %g , and %g.\n',x1,x2,x3)elseif D < 0Qs=sqrt(-Q);th=acosd(R/sqrt(-Q^3));x1=2*Qs*cosd(th/3)-a/3;x2=2*Qs*cosd(th/3+120)-a/3;x3=2*Qs*cosd(th/3+240)-a/3;fprintf('The roots are: %g , %g , and %g.\n',x1,x2,x3)end
Command Window:
(a)Enter the values of a3, a2, a1, and a0 as a vector: [5 -34.5 36.9 8.8]The roots are: 5.5 , -0.2 , and 1.6.
(b)Enter the values of a3, a2, a1, and a0 as a vector: [2 -10 24 -15]The equation has complex roots.
(c)Enter the values of a3, a2, a1, and a0 as a vector: [2 -1.4 -20.58 30.87]The roots are: -3.5 , 2.1 , and 2.1.
48 Chapter 6: Solved Problems
37. The overall grade in a course is determined from the grades of 10 homeworkassignments, 2 midterms, and a final exam, using the following scheme:Homeworks: Homework assignments are graded on a scale from 0 to 80.The grade of the two lowest assignments is dropped and the average of the 8assignments with the higher grades constitutes 20% of the course grade.Midterms and final exam: Midterms and final exams are graded on a scalefrom 0 to 100. If the average of the midterm scores is higher than, or thesame as, the score on the final exam, the average of the midterms constitutes40% of the course grade and the grade of the final exam constitutes 40% ofthe course grade. If the final exam grade is higher than the average of themidterms, the average of the midterms constitutes 30% of the course gradeand the grade of the final exam constitutes 50% of the course grade.
Write a computer program in a script file that determines the coursegrade for a student. The program first asks the user to enter the 10 home-work assignment grades (in a vector), two midterm grades (in a vector), andthe grade of the final. Then the program calculates a numerical course grade(a number between 0 and 100). Execute the program for the following cases:(a) Homework assignment grades: 65, 79, 80, 50, 71, 73, 61, 70, 69, 74. Mid-
term grades: 83, 91. Final exam: 84.(b) Homework assignment grades: 70, 69, 83, 45, 90, 89, 52, 78, 100, 87.
Midterm grades: 87, 72. Final exam: 90.
Solution
Script file:
clear, clcHW=input('Enter ten homework grades (0-80) in a vector ');MT=input('Enter two midterm grades (0-100) in a vector ');FE=input('Enter the final exam grade (0-100) ');HWsorted=sort(HW);HW8=HWsorted(3:10);HWtoFinalGrade=mean(HW8)/100*20;MTave=mean(MT); if MTave >= FE Grade=round(0.4*MTave+0.4*FE+HWtoFinalGrade);else Grade=round(0.3*MTave+0.5*FE+HWtoFinalGrade);endfprintf('Course grade: % i\n',Grade)
Chapter 6: Solved Problems 49
Command Window:Enter ten homework grades (0-80) in a vector [65 79 80 50
71 73 61 70 69 74];Enter two midterm grades (0-100) in a vector [83 91]Enter the final exam grade (0-100) 84Course grade: 83>> Enter ten homework grades (0-80) in a vector [70 69 83 45
90 89 52 78 100 87]Enter two midterm grades (0-100) in a vector [87 72]Enter the final exam grade (0-100) 90Course grade: 86>>
50 Chapter 6: Solved Problems
38. Keith number is a number (integer) that appears in a Fibonacci-likesequence that is based on its own decimal digits. For two-decimal digit num-bers (10 through 99) a Fibonacci-like sequence is created in which the firstelement is the tens digit and the second element is the units digit. The valueof each subsequent element is the sum of the previous two elements. If thenumber is a Keith number, then it appears in the sequence. For example, thefirst two-decimal digit Keith number is 14, since the corresponding Fibo-nacci-like sequence is 1, 4, 5, 9, 14. Write a MATLAB program that deter-mines and displays all the Keith numbers between 10 and 99.
Solution
Script file:
clear, clcp=1;for i=1:9 for j=0:9 N=10*i+j; a=[i, j]; for k=3:20 a(k)=a(k-2)+a(k-1); if a(k)==N KN(p)=N; p=p+1; break end if a(k)>N break end end endendKN
Command Window:
KN = 14 19 28 47 61 75>>
Chapter 6: Solved Problems 51
39. The following MATLAB commands creates a sine-shaped signal y(t) thatcontains random noise:t = 0:.05:10;y = sin(t)-0.1+0.2*rand(1,length(t));
Write a MATLAB program that use these commands to creates a noisysine-shaped signal. Then the program smooths the signal by using the three-points moving average method. In this method the value of every point i,except the first and last, is replaced by the average of the value of three adja-cent points (i–1, i, and i+1). Make a plot that display the noisy andsmoothed signals.
Solution
Script file:
clear, clct = 0:.05:10;y = sin(t)-0.1+0.2*rand(1,length(t)); n=length(t);ys=y;for k=1:10for j=2:n-1 ys(j)=(ys(j-1)+ys(j)+ys(j+1))/3;endendplot(t,y,t,ys,'linewidth',2) % Plot both signals.legend('Original signal','Signal with AWGN');
52 Chapter 6: Solved Problems
Figure: