Uploaded by Aballah Hassan

ch06ny eksempler

advertisement
Chapter 6
Solved Problems
1. Evaluate the following expressions without using MATLAB. Check the
answers with MATLAB.
(a)
(b)
(c)
(d)
Solution
>> % Part (a)
>> 6*4>32-3
ans =
0
>> % Part (b)
>> y=4*3-7<15/3>-1
y =
1
>> % Part (c)
>> y=2*(3<8/4+2)^2<(-2)
y =
0
>> % Part (d)
>> (5+~0)/3==3-~(10/5-2)
ans =
1
>>
1
2
Chapter 6: Solved Problems
2. Given:
,
,
. Evaluate the following expressions without
using MATLAB. Check the answers with MATLAB.
(a)
(b)
(c)
(d)
Solution
>> d=6
d =
6
>> e=4
e =
4
>> f=-2
f =
-2
>> % Part (a)
>> y=d+f>=e>d-e
y =
0
>> % Part (b)
>> y=e>d>f
y =
1
>> % Part (c)
>> y=e-d<=d-e==f/f
y =
1
>> % Part (d)
>> y=(d/e*f<f)>-1*(e-d)/f
y =
1
>>
3
Chapter 6: Solved Problems
3. Given: v = [–2 4 1 0 2 1 2 ] and w = [2 5 0 1 2 –1 3 ]. Evaluate the following expressions without using MATLAB. Check the answers with MATLAB.
(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
>> w=[2 5 0 1 2 -1 3]
w =
2
5
0
>> % Part (a)
>> ~v==~w
ans =
1
1
0
>> % Part (b)
>> w>=v
ans =
1
1
0
>> % Part (c)
>> v>~1*w
ans =
0
1
1
>> % Part (d)
>> v>-1*w
ans =
0
1
1
>>
0
2
1
2
1
2
-1
3
0
1
1
1
1
1
0
1
0
1
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 a
vector u that is made up of the elements of v that are smaller than or equal
to 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 the
answers 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&-3
ans =
1
>> % Part (b)
>> 7>6&~0<=2
ans =
1
>> % Part (c)
>> ~4<5|0>=12/6
ans =
1
>> % Part (d)
>> -7<-5<-2&2+3<=15/3
ans =
0
>>
5
Chapter 6: Solved Problems
6. Use loops to create a
matrix in which the value of each element is two
times its row number minus three times its column number. For example, the
value of element (2,5) is
.
Solution
Script File
for i=1:4
for j=1:6
A(i,j)=2*i-3*j;
end
end
A
Command Window:
A =
-1
1
3
5
-4
-2
0
2
-7
-5
-3
-1
-10
-8
-6
-4
-13
-11
-9
-7
-16
-14
-12
-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 divisible
by 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);
end
end
S
6
Chapter 6: Solved Problems
Command Window:
v =
Columns 1 through 12
10
-10
0
8
10
14
-10
Columns 13 through 24
13
-11
18
-6
14
3
2
Columns 25 through 30
17
-9
11
10
S =
-24
16
19
2
-15
-14
-12
-10
5
-1
-6
-5
-
3
8. Write a program that asks the user to input a vector of integers of arbitrary
length. Then, using a for loop the program examine each element of the vector. If the element is positive its value is doubled. If the element is negative
its value is tripled. The program displays the vector that was entered and the
modified vector. Execute the program and when the program ask the user to
input a vector type randi([-10 20],1,19). This creates a 19-element
vector 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);
end
end
vNew=v
Command Window:
v =
Columns 1 through 15
7
Chapter 6: Solved Problems
-8
-9
6
14
18
-6
0
-5
14
-1
6
-5
Columns 16 through 19
8
-2
10
11
vNew =
Columns 1 through 15
-24
-27
12
28
36
-18
0
-15
28
-3
12
-15
Columns 16 through 19
16
-6
20
22
7
4
-10
14
8
-30
9. Write a program that asks the user to input a vector of integers of arbitrary
length. Then, using a for loop the program eliminates all the negative elements. The program displays the vector that was entered and the modified
vector, and a message that says how many elements were eliminated. Execute the program and when the program ask the user to input a vector type
randi([-15 20],1,25). This creates a 25-element vector with random
integers 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);
end
end
elim=n-j;
vNew
fprintf('%.0f elements were eliminated.\n',elim)
Command Window:
v =
Columns 1 through 13
8
Chapter 6: Solved Problems
17
6
7
15
13
14
2
-9
20
Columns 14 through 25
10
3
1
-13
9
14
14
11
vNew =
Columns 1 through 13
17
6
7
15
13
10
3
1
9
Columns 14 through 17
3
14
14
11
8 elements were eliminated.
5
-9
-7
16
-
-14
-13
3
-12
5
16
2
20
10. The daily high temperature (°F) in New York City and Denver, Colorado
during the month of January 2014 is given in the vectors below (data from
the 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 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 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 following
information:
(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, clc
NYC = [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
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.
9
10
Chapter 6: Solved Problems
11. The Pascal’s triangle can be displayed as elements in a
lower-triangular matrix as shown on the right. Write a
MATLAB program that creates a
matrix that displays n rows of Pascal’s triangle. Use the program to create
4 and 7 rows Pascal’s triangles. (One way to calculate the
value 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(j1)*factorial(i-j));
end
end
pt
Command Window:
pt =
1
1
1
1
1
1
0
1
2
3
4
5
0
0
1
3
6
10
0
0
0
1
4
10
0
0
0
0
1
5
0
0
0
0
0
1
1
1
1
1
1
1
0
1
2
3
4
5
0
0
1
3
6
10
0
0
0
1
4
10
0
0
0
0
1
5
0
0
0
0
0
1
11
Chapter 6: Solved Problems
12. Tribonacci numbers are the numbers in a sequence in which the first three
elements are 0, 1, and 1, and the value of each subsequent element is the sum
of the previous three elements:
0, 1, 1, 2, 4, 7, 13, 24, ...
Write a MATLAB program in a script file that determines and displays the
first 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]));
end
F
Command Window:
F =
Columns 1 through 6
0
1
7
Columns 7 through 12
13
24
274
Columns 13 through 18
504
927
10609
Columns 19 through 24
19513
35890
223317
410744
Column 25
755476
1
2
4
44
81
149
1705
3136
66012
5768
121415
12
Chapter 6: Solved Problems
13. The reciprocal Fibonacci constant ψ is defined by the infinite sum:
ψ =
∞

n=1
where F n are the Fibonacci numbers 1, 1, 2, 3, 5, 8, 13, ... . Each element in
this sequence of numbers is the sum of the previous two. Start by setting the
first two elements equal to 1, then
. Write a MATLAB program in a script file that calculates ψ for a given n. Execute the program for
n = 10, 50, 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);
end
xi=sum(1./F)
Command Window:
xi =
3.359885666243178
14. The value of π can be estimated from:
∞

n=0
Write a program (using a loop) that determines π for a given n. Run the program with n = 10, n = 100, and n = 1000. Compare the result with pi. (Use
format long.)
Solution
Script File:
format long
n=input('Enter a value for n
S=0;
for i=0:n
S=S+(-1)^i/(2*i+1)^3;
end
');
13
Chapter 6: Solved Problems
ESpi=(32*S)^(1/3)
Command Window:
Enter a value for n
ESpi =
3.141642788603785
>> ed6_HW6_14
Enter a value for n
ESpi =
3.141592719141050
>> ed6_HW6_14
Enter a value for n
ESpi =
3.141592653657139
10
100
1000
15. The value of π can be estimated from the expression:
Write a MATLAB program in a script file that determine π for any number
of terms. The program asks the user to enter the number of terms, and then
calculates 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 long
n=5;
S2=0;
S=1;
for i=1:n
S2=sqrt(2+S2);
S=S*S2/2;
end
piEst=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 elements
with integers between 10 and 30, (b) replaces all the elements that are not
even integers with random integers between 10 and 30, (c) repeats (b) until
all the elements are even integers. The program should also count how many
times (b) is repeated before all the elements are even integers. When done,
the program displays the vector and a statement that states how many iterations 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
end
end
vFinal=vInitial
fprintf('%.0f iterations were done.\n',i-1)
Command Window:
15
Chapter 6: Solved Problems
vInitial =
27
12
22
17
26
20
19
30
10
30
13
24
22
27
vFinal =
10
12
22
28
26
20
16
30
10
30
14
24
22
12
4 iterations were done.
20
24
28
17
17
23
20
24
28
18
30
12
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 rearranges
the elements of x in order from the smallest to the largest. Do not use MATLAB’s built-in function sort.
Solution
Script file:
clear, clc
x=[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
end
end
x
Command Window:
x =
9.0000
4.6000
0.2000
x =
-6.1000
-1.5000
1.1000
-2.1000
13.4000
5.0000
-1.5000
13.3000
-6.1000
-2.1000
10.0000
0.2000
1.1000
16
Chapter 6: Solved Problems
4.6000
13.4000
5.0000
9.0000
10.0000
13.3000
>>
18. The Pythagorean theorem states that a 2 + b 2 = c 2 . Write a MATLAB program in a script file that finds all the combinations of triples a, b, and c that
are positive integers all smaller or equal to 50 that satisfy the Pythagorean
theorem. Display the results in a three-column table in which every row corresponds to one triple. The first three rows of the table are:
3 4 5
5 12 13
6 8 10
Solution
Script file:
clear, clc
id=1;
for k=1:50
for j=k+1:50
for i=j+1:50
if i^2==k^2+j^2
a(id)=k;
b(id)=j;
c(id)=i;
id=id+1;
end
end
end
end
table=[a' b' c']
Command Window:
table =
3
5
6
7
8
9
9
4
12
8
24
15
12
40
5
13
10
25
17
15
41
17
Chapter 6: Solved Problems
10
12
12
14
15
15
16
18
20
21
24
27
30
24
16
35
48
20
36
30
24
21
28
32
36
40
26
20
37
50
25
39
34
30
29
35
40
45
50
>>
19. Write a MATLAB program in a script file that finds and displays all the
numbers between 100 and 999 whose product of digits is 6 times the sum of
the digits. (e.g. 347 since
). Use a for loop in the program. 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
end
end
Command Window:
n =
18
Chapter 6: Solved Problems
268
n =
286
n =
347
n =
374
n =
437
n =
473
n =
628
n =
682
n =
734
n =
743
n =
826
n =
862
20. A safe prime is a prime number that can be written in the form
where p is
also a prime number. For example, 47 is a safe prime since
and 23
is also a prime number. Write a computer program that finds and displays all the
safe primes between 1 and 1000. Do not use MATLAB’s built-in function
isprime.
Solution
Script file:
clear, clc
k=1;
for n=1:500;
nispr=1;
nsafeisPrime=0;
for i=2:fix(n/2)
if rem(n,i)==0
nispr=0;
19
Chapter 6: Solved Problems
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
end
SafePrimeNum
Command Window:
SafePrimeNum =
Columns 1 through 7
3
5
7
11
Columns 8 through 14
83
107
167
179
Columns 15 through 21
359
383
467
479
Columns 22 through 26
719
839
863
887
23
47
59
227
263
347
503
563
587
983
20
Chapter 6: Solved Problems
21. Sexy primes are two prime numbers that the difference between them is 6. For
example, 23 and 29 are sexy primes since
. Write a computer program that finds all the sexy primes between 1 and 300. The numbers should be
displayed in a two-column matrix where each row display one pair. Do not use
MATLAB’s built-in function isprime.
Solution
Script file:
clear, clc
k=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
end
SexyPrimeNum
Command Window:
Chapter 6: Solved Problems
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
>>
21
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 computer
program that finds all the Mersenne primes between 1 and 10,000. Do not use
MATLAB’s built-in function isprime.
Solution
Script file:
clear, clc
k=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
end
end
MersennePrimes
Command Window:
MersennePrimes =
3
7
31
127
8191
23
Chapter 6: Solved Problems
23. A perfect number is a positive integer that is equal to the sum of its positive divisors except the number itself. The first two perfect numbers are 6 and 28 since
and
. Write a computer program that finds the
first four perfect numbers.
Solution
Script file:
clear, clc
j=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;
end
end
PerfectN
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 standard
deviation (Sd) of the scores, which are rounded to the nearest integer. Then,
the program determines the letter grade of each of the scores according to
the following scheme:
Score (%)
Letter grade
Score (%)
A
B
Letter grade
Score (%)
C
D
F
The program displays the values of Av and Sd followed by a list that shows
the scores and the corresponding letter grade (e.g. 72% Letter grade C).
Letter grade
Solution
Script file:
clear,clc
G=[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
25
Chapter 6: Solved Problems
end
Command Window:
Average grade is
71%. Standard deviation is
72%
81%
44%
68%
90%
53%
80%
75%
74%
65%
50%
92%
85%
69%
41%
73%
70%
86%
61%
65%
79%
94%
69%
>>
C
B
F
C
A
D
B
C
C
C
F
A
B
C
F
C
C
B
D
C
B
A
C
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
Letter
grade
grade
grade
grade
grade
grade
grade
grade
grade
grade
grade
grade
grade
grade
grade
grade
grade
grade
grade
grade
grade
grade
grade
14%.
26
Chapter 6: Solved Problems
25. The Taylor series expansion for ax is:
∞

n=0
Write a MATLAB program that determines ax using the Taylor series
expansion. The program asks the user to type a value for x. Use a loop for
adding the terms of the Taylor series. If cn is the nth term in the series, then
the sum Sn of the n terms is
. In each pass calculate the estimated error E given by
. Stop adding terms when
The program displays the value of ax. Use the program to calculate:
(b) 6.31.7
(a) 23.5
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;
end
S
Command Window:
Enter a value for a 2
Enter a value for x 3.5
S =
11.313707964994668
Calculator value: 11.3137085
Enter a value for a
Enter a value for x
6.3
1.7
.
Chapter 6: Solved Problems
S =
22.849612550742957
Calculator value: 22.84961748
26. Write a MATLAB program in a script file that finds a positive integer n such
that the sum of all the integers 1 + 2 + 3 + … + n is a number between 100
and 1000 whose three digits are identical. As output, the program displays
the 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
end
end
Command Window:
n =
36
Sm =
666
27
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.65
for medium, and 0.8 for high fitness). Write a program in a script file that
determines the THR. The program asks users to enter their gender (male or
female), 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 training 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;
end
switch 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)));
end
THR=round((Mhr-Rhr)*Intn+Rhr)
Command Window:
(a)
Please enter gender (Male or Female):
Male
29
Chapter 6: Solved Problems
Enter age: 19
Enter resting heart rate: 64
Enter fitness level (low, medium, or high):
THR =
147
medium
(b)
Please enter gender (Male or Female): Female
Enter age: 20
Enter resting heart rate: 63
Enter fitness level (low, medium, or high): high
THR =
162
28. Body Mass Index (BMI) is a measure of obesity. In standard units, it is calculated by the formula
where W is weight in pounds, and H is height in inches. The obesity classification is:
BMI
Classification
Below 18.5
Underweight
18.5 to 24.9
Normal
25 to 29.9
Overweight
30 and above
Obese
Write a program in a script file that calculates the BMI of a person. The program asks the person to enter his or her weight (lb) and height (in.). The
program displays the result in a sentence that reads: “Your BMI value is
XXX, which classifies you as SSSS,” where XXX is the BMI value rounded
to the nearest tenth, and SSSS is the corresponding classification. Use the
program 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:
30
Chapter 6: Solved Problems
clear, clc
W=input('Please input your weight in lb: ');
h=input('Please input your height in in.: ');
BMI=703*W/h^2;
if BMI<18.5
fprintf('\nYour BMI value is %.1f, which classifies
as underweight\n\n',BMI)
elseif BMI<25
fprintf('\nYour BMI value is %.1f, which classifies
as normal\n\n',BMI)
elseif BMI<30
fprintf('\nYour BMI value is %.1f, which classifies
as overweight\n\n',BMI)
else
fprintf('\nYour BMI value is %.1f, which classifies
as obese\n\n',BMI)
end
Command Window:
Please input your weight in lb: 180
Please input your height in in.: 74
Your BMI value is 23.1, which classifies you as normal
Please input your weight in lb: 150
Please input your height in in.: 61
Your BMI value is 28.3, which classifies you as overweight
>>
you
you
you
you
31
Chapter 6: Solved Problems
29. Write a program in a script file that calculates the cost of renting a car
according to the following price schedule:
Sedan
Duration of rent
Daily
rate
SUV
Free
Cost of
miles Additional
(per day) mile
Daily
rate
Free
Cost of
miles Additional
(per day) 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
The program asks the user to enter the type of car (Sedan or SUV), the
number of days, and the number of miles driven. The program then displays
the cost (rounded to cents) for the rent. Run the program three times for the
following cases:
(a) Sedan, 10 days, 769 miles. (b) SUV, 32 days, 4,056 miles.
(c) Sedan, 3 days, 511 miles.
Solution
Script file:
clear, clc
T=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
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
end
end
fprintf('The cost of the rent is $%5.2f\n',cost)
Command Window:
Enter the type of car (Sedan, or SUV) Sedan
Enter the number of days 10
Enter the number of miles 769
The cost of the rent is $690.00
>>
Enter the type of car (Sedan, or SUV) SUV
Enter the number of days 32
Chapter 6: Solved Problems
Enter the number of miles 4056
The cost of the rent is $2164.64
>>
Enter the type of car (Sedan, or SUV) Sedan
Enter the number of days 3
Enter the number of miles 511
The cost of the rent is $423.99
>>
33
34
Chapter 6: Solved Problems
30. Write a program that determines the change given back to a customer in a
self-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 displays the number as the amount to be paid. The program then asks the user
to enter payment, which can be one $1 bill, one $5 bill, one $10 bill, one $20
bill, or one $50 bill. If the payment is less than the amount to be paid, an
error message is displayed. If the payment is sufficient, the program calculates 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. For
example, if the amount to be paid is $2.33 and a $10 bill is entered as payment, 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, clc
AmToPy=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);
end
end
disp('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))
35
Chapter 6: Solved Problems
fprintf('%2.0f nickels\n',R(7))
fprintf('%2.0f cents\n',R(8))
end
Command Window:
The amount to be paid is: $13.93
Please enter payment in dollars (1, 5, 10, 20 or 50)
The 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.35
Please enter payment in dollars (1, 5, 10, 20 or 50)
The 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.02
Please enter payment in dollars (1, 5, 10, 20 or 50)
The change is:
0 $20 bills
0 $10 bills
1 $5 bills
4 $1 bills
3 quarters
2 dimes
0 nickels
3 cents
>>
20
50
50
36
Chapter 6: Solved Problems
31. The concentration of a drug in the body C P can be modeled by the equation:
where D G is the dosage administered (mg), V d is the volume of distribution
(L), k a is the absorption rate constant (h–1), k e is the elimination rate constant (h–1), and t is the time (h) since the drug was administered. For a certain drug, the following quantities are given: D G = 150 mg, V d = 50 L,
k a = 1.6 h–1, and k e = 0.4 h–1.
(a) A single dose is administered at t = 0. Calculate and plot C P versus t
for 10 hours.
(b) A first dose is administered at t = 0 , and subsequently four more doses
are administered at intervals of 4 hours (i.e., at t = 4, 8, 12, 16 ). Calculate and plot C P versus t for 24 hours.
Solution
Part (a)
Script file:
clear, clc
t=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)')
Chapter 6: Solved Problems
Figure:
Part (b)
Script file:
clear, clc
t=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(-
37
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)));
end
end
plot(t,Cp)
xlabel('Time (hr)')
ylabel('Drug Concentration (mg/L)')
Figure:
39
Chapter 6: Solved Problems
32. One numerical method for calculating the cubic root of a number, 3 P is Halley’s method. The solution process starts by choosing a value x 1 as a first estimate of the solution. Using this value, a second, more accurate value x 2 is
calculated with,
which is then used for calculating a
third, still more accurate value x 3 , and so on. The general equation for calculating the value of x i + 1 from the value of x i is
.
Write a MATLAB program that calculates the cubic root of a number. In the
program use x 1 = P for the first estimate of the solution. Then, by using the
general 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)
3
800
(b)
3
59071
(c)
Solution
Script 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;
end
fprintf ('the qubic root of %g is %g\n',P,QRP)
Command Window:
Enter a number for calculating its cubic root:
the qubic root of 800 is 9.28318
800
Enter a number for calculating its cubic root:
the qubic root of 59071 is 38.9456
59071
Enter a number for calculating its cubic root:
the qubic root of -31.55 is -3.15985
-31.55
40
Chapter 6: Solved Problems
33. Write a program in a script file that converts a measure of area given in units
of either m2, cm2, in2, ft2, yd2, or acre to the equivalent quantity in different
units specified by the user. The program asks the user to enter a numerical
value for the size of an area, its current units, and the desired new units. The
output 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, clc
Ain=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 AinUnits
case '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;
end
switch AoutUnits
case 'sqm'
Aout=Asqcm*1E-4;
case 'sqcm'
Aout=Asqcm;
case 'sqin'
Aout=Asqcm/2.54^2;
Chapter 6: Solved Problems
case 'sqft'
Aout=Asqcm/(2.54*12)^2;
case 'sqyd'
Aout=Asqcm/(3*2.54*12)^2;
otherwise
error=1;
end
if 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: 55
Enter the current units (sqm, sqcm, sqin, sqft or sqyd):
sqin
Enter the new units (sqm, sqcm, sqin, sqft or sqyd):
sqcm
A= 354.838 sqcm
>>
Enter the value of the area to be converted: 2400
Enter the current units (sqm, sqcm, sqin, sqft or sqyd):
sqft
Enter the new units (sqm, sqcm, sqin, sqft or sqyd): sqm
A= 222.967 sqm
>>
Enter the value of the area to be converted: 300
Enter the current units (sqm, sqcm, sqin, sqft or sqyd):
sqcm
Enter the new units (sqm, sqcm, sqin, sqft or sqyd):
sqyd
A= 0.0358797 sqyd
>>
41
42
Chapter 6: Solved Problems
34. In a one-dimensional random walk, the position x of a walker is computed
by:
xj = xj + s
where s is a random number. Write a program that calculates the number of
steps required for the walker to reach a boundary
. Use MATLAB’s
built-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 B = 10 .
Solution
Script File:
clear, clc
for j=1:100
x=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;
end
AveNumSteps=mean(steps)
Command Window:
AveNumSteps =
123.7700
>>
Chapter 6: Solved Problems
35. The Sierpinski triangle can be implemented in MATLAB by plotting points
iteratively according to one of the following three rules that are selected randomly with equal probability.
Rule 1:
x n + 1 = 0.5x n, y n + 1 = 0.5y n
Rule 2:
x n + 1 = 0.5x n + 0.25 ,
Rule 3:
x n + 1 = 0.5x n + 0.5 , y n + 1 = 0.5y n
Write a program in a script file that calculates the x and y vectors and then
plots y versus x as individual points (use plot(x,y,‘^’)). Start with
x 1 = 0 and y 1 = 0 . Run the program four times with 10, 100, 1,000, and
10,000 iterations.
Solution
Script file:
clear, clc
x(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);
end
end
plot(x,y,'^')
axis equal
43
44
Chapter 6: Solved Problems
Figure 10 iterations:
Figure 100 iterations:
Figure 1000 iterations:
Chapter 6: Solved Problems
Figure 10,000 iterations:
45
46
Chapter 6: Solved Problems
36. The roots of a cubic equation
using the following procedure:
Set:
,
, and
Calculate:
can be calculated
.
,
where
If
If
and
.
the equation has complex roots.
all roots are real and at least two are equal. The roots are given by:
If
,
, and
all roots are real and are given by:
,
.
, and
, where
.
Write a MATLAB program that determines the real roots of a cubic equation. As input the program asks the user to enter the values of a3, a2, a1, and
a0 as a vector. The program then calculates the value of D. If the equations
has complex roots the message “The equation has complex roots” is displayed. Otherwise the real roots are calculated and displayed. Use the program to solve the following equations:
(a)
(c)
(b)
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;
end
if 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
x3=x2;
fprintf('The roots are: %g , %g , and
%g.\n',x1,x2,x3)
elseif D < 0
Qs=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.
47
48
Chapter 6: Solved Problems
37. The overall grade in a course is determined from the grades of 10 homework
assignments, 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 8
assignments with the higher grades constitutes 20% of the course grade.
Midterms and final exam: Midterms and final exams are graded on a scale
from 0 to 100. If the average of the midterm scores is higher than, or the
same as, the score on the final exam, the average of the midterms constitutes
40% of the course grade and the grade of the final exam constitutes 40% of
the course grade. If the final exam grade is higher than the average of the
midterms, the average of the midterms constitutes 30% of the course grade
and the grade of the final exam constitutes 50% of the course grade.
Write a computer program in a script file that determines the course
grade for a student. The program first asks the user to enter the 10 homework assignment grades (in a vector), two midterm grades (in a vector), and
the 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. Midterm 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, clc
HW=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);
end
fprintf('Course grade: % i\n',Grade)
Chapter 6: Solved Problems
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) 84
Course 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) 90
Course grade:
86
>>
49
50
Chapter 6: Solved Problems
38. Keith number is a number (integer) that appears in a Fibonacci-like
sequence that is based on its own decimal digits. For two-decimal digit numbers (10 through 99) a Fibonacci-like sequence is created in which the first
element is the tens digit and the second element is the units digit. The value
of each subsequent element is the sum of the previous two elements. If the
number is a Keith number, then it appears in the sequence. For example, the
first two-decimal digit Keith number is 14, since the corresponding Fibonacci-like sequence is 1, 4, 5, 9, 14. Write a MATLAB program that determines and displays all the Keith numbers between 10 and 99.
Solution
Script file:
clear, clc
p=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
end
end
KN
Command Window:
KN =
14
>>
19
28
47
61
75
Chapter 6: Solved Problems
39. The following MATLAB commands creates a sine-shaped signal y(t) that
contains 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 noisy
sine-shaped signal. Then the program smooths the signal by using the threepoints 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 adjacent points (i–1, i, and i+1). Make a plot that display the noisy and
smoothed signals.
Solution
Script file:
clear, clc
t = 0:.05:10;
y = sin(t)-0.1+0.2*rand(1,length(t));
n=length(t);
ys=y;
for k=1:10
for j=2:n-1
ys(j)=(ys(j-1)+ys(j)+ys(j+1))/3;
end
end
plot(t,y,t,ys,'linewidth',2) % Plot both signals.
legend('Original signal','Signal with AWGN');
51
52
Chapter 6: Solved Problems
Figure:
Download