SlideShare ist ein Scribd-Unternehmen logo
1 von 52
Downloaden Sie, um offline zu lesen
1
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
>>
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
>>
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==~w
ans =
1 1 0 0 1 1 1
>> % Part (b)
>> w>=v
ans =
1 1 0 1 1 0 1
>> % Part (c)
>> v>~1*w
ans =
0 1 1 0 1 1 1
>> % Part (d)
>> v>-1*w
ans =
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 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
>>
Chapter 6: Solved Problems 5
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 -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 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 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 3
S =
-24
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 vec-
tor. 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
Chapter 6: Solved Problems 7
-8 -9 6 14 18 -6 7 4 -10
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 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 arbitrary
length. Then, using a for loop the program eliminates all the negative ele-
ments. The program displays the vector that was entered and the modified
vector, 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 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 5 -9 -7 16 -
14 2 -9 20
Columns 14 through 25
10 3 1 -13 9 -14 -13 3 -12
14 14 11
vNew =
Columns 1 through 13
17 6 7 15 13 5 16 2 20
10 3 1 9
Columns 14 through 17
3 14 14 11
8 elements were eliminated.
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 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 a
lower-triangular matrix as shown on the right. Write a
MATLAB program that creates a matrix that dis-
plays 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(j-
1)*factorial(i-j));
end
end
pt
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 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
Chapter 6: Solved Problems 11
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 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 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 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);
end
xi=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. (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
ψ
ψ
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 10
ESpi =
3.141642788603785
>> ed6_HW6_14
Enter a value for n 100
ESpi =
3.141592719141050
>> ed6_HW6_14
Enter a value for n 1000
ESpi =
3.141592653657139
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 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
end
end
vFinal=vInitial
fprintf('%.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 rearranges
the 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, 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 -1.5000 13.4000 13.3000 -2.1000
4.6000 1.1000 5.0000 -6.1000 10.0000
0.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.3000
13.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 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 cor-
responds 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 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 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 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
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;
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
end
SafePrimeNum
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. For
example, 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 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 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 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
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 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:
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).
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 An',G(i))
elseif G(i) > Av+0.5*S & G(i) < Av+1.3*S
fprintf('%3i%% Letter grade Bn',G(i))
elseif G(i) > Av-0.5*S & G(i) < Av+0.5*S
fprintf('%3i%% Letter grade Cn',G(i))
elseif G(i) > Av-1.3*S & G(i) < Av-0.5*S
fprintf('%3i%% Letter grade Dn',G(i))
elseif G(i) < Av-1.3*S
fprintf('%3i%% Letter grade Fn',G(i))
end
Score (%)
Letter grade A B
Score (%)
Letter grade C D
Score (%)
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 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 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;
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 6.3
Enter 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 such
that the sum of all the integers 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
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.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 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;
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
Chapter 6: Solved Problems 29
Enter age: 19
Enter resting heart rate: 64
Enter fitness level (low, medium, or high): medium
THR =
147
(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 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.). 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:
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, 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 you
as underweightnn',BMI)
elseif BMI<25
fprintf('nYour BMI value is %.1f, which classifies you
as normalnn',BMI)
elseif BMI<30
fprintf('nYour BMI value is %.1f, which classifies you
as overweightnn',BMI)
else
fprintf('nYour BMI value is %.1f, which classifies you
as obesenn',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
>>
Chapter 6: Solved Problems 31
29. Write a program in a script file that calculates the cost of renting a car
according to the following price schedule:
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
Duration of rent
Sedan SUV
Daily
rate
Free
miles
(per day)
Cost of
Additional
mile
Daily
rate
Free
miles
(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
end
end
fprintf('The cost of the rent is $%5.2fn',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 33
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
>>
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 dis-
plays 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 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. For
example, 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, clc
AmToPy=randi(5000)/100;
fprintf('The amount to be paid is: $%5.2fn',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 billsn',R(1))
fprintf('%2.0f $10 billsn',R(2))
fprintf('%2.0f $5 billsn',R(3))
fprintf('%2.0f $1 billsn',R(4))
fprintf('%2.0f quartersn',R(5))
fprintf('%2.0f dimesn',R(6))
Chapter 6: Solved Problems 35
fprintf('%2.0f nickelsn',R(7))
fprintf('%2.0f centsn',R(8))
end
Command Window:
The amount to be paid is: $13.93
Please enter payment in dollars (1, 5, 10, 20 or 50) 20
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) 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) 50
The 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, 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)')
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, 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(-
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:
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 a
third, 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 the
program use 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) (b) (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 %gn',P,QRP)
Command Window:
Enter a number for calculating its cubic root: 800
the qubic root of 800 is 9.28318
Enter a number for calculating its cubic root: 59071
the qubic root of 59071 is 38.9456
Enter a number for calculating its cubic root: -31.55
the qubic root of -31.55 is -3.15985
P
3
x1
x2
x3
xi 1
+ xi
x1 P
=
800
3 59071
3
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 41
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 %sn',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
>>
42 Chapter 6: Solved Problems
34. In a one-dimensional random walk, the position x of a walker is computed
by:
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 .
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
>>
xj xj s
+
=
B 10
=
Chapter 6: Solved Problems 43
35. The Sierpinski triangle can be implemented in MATLAB by plotting points
iteratively 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 then
plots y versus x as individual points (use plot(x,y,‘^’)). Start with
and . 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
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 calculated
using 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, 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 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;
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 47
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.
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 home-
work 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. 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, 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: % in',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) 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
>>
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 num-
bers (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 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, 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 51
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 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 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');
52 Chapter 6: Solved Problems
Figure:

Weitere ähnliche Inhalte

Was ist angesagt?

Mechanics of Materials 8th Edition R.C. Hibbeler
Mechanics of Materials 8th Edition R.C. HibbelerMechanics of Materials 8th Edition R.C. Hibbeler
Mechanics of Materials 8th Edition R.C. HibbelerBahzad5
 
Solution Manul for Structural Analysis in SI Units 10th Edition by Russell Hi...
Solution Manul for Structural Analysis in SI Units 10th Edition by Russell Hi...Solution Manul for Structural Analysis in SI Units 10th Edition by Russell Hi...
Solution Manul for Structural Analysis in SI Units 10th Edition by Russell Hi...physicsbook
 
Structural Analysis 8th Edition Solutions Manual
Structural Analysis 8th Edition Solutions ManualStructural Analysis 8th Edition Solutions Manual
Structural Analysis 8th Edition Solutions ManualBahzad5
 
9789810682460 sm 06
9789810682460 sm 069789810682460 sm 06
9789810682460 sm 06aryaanuj1
 
Instructor solution manual for chapter 10 indeterminate structures "structur...
Instructor solution manual for chapter 10  indeterminate structures "structur...Instructor solution manual for chapter 10  indeterminate structures "structur...
Instructor solution manual for chapter 10 indeterminate structures "structur...Omar Daher
 
8- Center of Gravity and Centroid.pdf
8- Center of Gravity and Centroid.pdf8- Center of Gravity and Centroid.pdf
8- Center of Gravity and Centroid.pdfYusfarijerjis
 
Fluid mechanics 2nd edition hibbeler solutions manual
Fluid mechanics 2nd edition hibbeler solutions manualFluid mechanics 2nd edition hibbeler solutions manual
Fluid mechanics 2nd edition hibbeler solutions manualGyn172
 
Structural Analysis, Hibbeler, 8th ed Textbook
Structural Analysis, Hibbeler, 8th ed Textbook Structural Analysis, Hibbeler, 8th ed Textbook
Structural Analysis, Hibbeler, 8th ed Textbook Bahzad5
 
68908191 ejercicios-resueltos-derivacion
68908191 ejercicios-resueltos-derivacion68908191 ejercicios-resueltos-derivacion
68908191 ejercicios-resueltos-derivacionmilico
 
STRUCTURAL ANALYSIS NINTH EDITION R. C. HIBBELER
STRUCTURAL ANALYSIS NINTH EDITION R. C. HIBBELERSTRUCTURAL ANALYSIS NINTH EDITION R. C. HIBBELER
STRUCTURAL ANALYSIS NINTH EDITION R. C. HIBBELERBahzad5
 
Numerical Analysis (Solution of Non-Linear Equations)
Numerical Analysis (Solution of Non-Linear Equations)Numerical Analysis (Solution of Non-Linear Equations)
Numerical Analysis (Solution of Non-Linear Equations)Asad Ali
 
Beer vector mechanics for engineers statics 10th solutions
Beer vector mechanics for engineers statics 10th solutionsBeer vector mechanics for engineers statics 10th solutions
Beer vector mechanics for engineers statics 10th solutionsmazzybio512
 

Was ist angesagt? (20)

MOMENT OF INERIA
MOMENT OF INERIAMOMENT OF INERIA
MOMENT OF INERIA
 
Mechanics of Materials 8th Edition R.C. Hibbeler
Mechanics of Materials 8th Edition R.C. HibbelerMechanics of Materials 8th Edition R.C. Hibbeler
Mechanics of Materials 8th Edition R.C. Hibbeler
 
Chapter 7
Chapter 7Chapter 7
Chapter 7
 
Solution Manul for Structural Analysis in SI Units 10th Edition by Russell Hi...
Solution Manul for Structural Analysis in SI Units 10th Edition by Russell Hi...Solution Manul for Structural Analysis in SI Units 10th Edition by Russell Hi...
Solution Manul for Structural Analysis in SI Units 10th Edition by Russell Hi...
 
Structural Analysis 8th Edition Solutions Manual
Structural Analysis 8th Edition Solutions ManualStructural Analysis 8th Edition Solutions Manual
Structural Analysis 8th Edition Solutions Manual
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
9789810682460 sm 06
9789810682460 sm 069789810682460 sm 06
9789810682460 sm 06
 
Instructor solution manual for chapter 10 indeterminate structures "structur...
Instructor solution manual for chapter 10  indeterminate structures "structur...Instructor solution manual for chapter 10  indeterminate structures "structur...
Instructor solution manual for chapter 10 indeterminate structures "structur...
 
8- Center of Gravity and Centroid.pdf
8- Center of Gravity and Centroid.pdf8- Center of Gravity and Centroid.pdf
8- Center of Gravity and Centroid.pdf
 
Calculo 3 curvas d nivel
Calculo 3 curvas d nivelCalculo 3 curvas d nivel
Calculo 3 curvas d nivel
 
estatica
estaticaestatica
estatica
 
Fluid mechanics 2nd edition hibbeler solutions manual
Fluid mechanics 2nd edition hibbeler solutions manualFluid mechanics 2nd edition hibbeler solutions manual
Fluid mechanics 2nd edition hibbeler solutions manual
 
Chapter16 140816162809-phpapp01
Chapter16 140816162809-phpapp01Chapter16 140816162809-phpapp01
Chapter16 140816162809-phpapp01
 
Structural Analysis, Hibbeler, 8th ed Textbook
Structural Analysis, Hibbeler, 8th ed Textbook Structural Analysis, Hibbeler, 8th ed Textbook
Structural Analysis, Hibbeler, 8th ed Textbook
 
68908191 ejercicios-resueltos-derivacion
68908191 ejercicios-resueltos-derivacion68908191 ejercicios-resueltos-derivacion
68908191 ejercicios-resueltos-derivacion
 
STRUCTURAL ANALYSIS NINTH EDITION R. C. HIBBELER
STRUCTURAL ANALYSIS NINTH EDITION R. C. HIBBELERSTRUCTURAL ANALYSIS NINTH EDITION R. C. HIBBELER
STRUCTURAL ANALYSIS NINTH EDITION R. C. HIBBELER
 
Chapter 04
Chapter 04Chapter 04
Chapter 04
 
Numerical Analysis (Solution of Non-Linear Equations)
Numerical Analysis (Solution of Non-Linear Equations)Numerical Analysis (Solution of Non-Linear Equations)
Numerical Analysis (Solution of Non-Linear Equations)
 
Beer vector mechanics for engineers statics 10th solutions
Beer vector mechanics for engineers statics 10th solutionsBeer vector mechanics for engineers statics 10th solutions
Beer vector mechanics for engineers statics 10th solutions
 

Ähnlich wie Solution of matlab chapter 6

BS LAB Manual (1).pdf
BS LAB Manual  (1).pdfBS LAB Manual  (1).pdf
BS LAB Manual (1).pdfssuser476810
 
Name _______________________________ Class time __________.docx
Name _______________________________    Class time __________.docxName _______________________________    Class time __________.docx
Name _______________________________ Class time __________.docxrosemarybdodson23141
 
Matrix Multiplication(An example of concurrent programming)
Matrix Multiplication(An example of concurrent programming)Matrix Multiplication(An example of concurrent programming)
Matrix Multiplication(An example of concurrent programming)Pramit Kumar
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentationManchireddy Reddy
 
Sample Exam Questions on Python for revision
Sample Exam Questions on Python for revisionSample Exam Questions on Python for revision
Sample Exam Questions on Python for revisionafsheenfaiq2
 
Matlab solved tutorials 2017 june.
Matlab solved tutorials  2017 june.Matlab solved tutorials  2017 june.
Matlab solved tutorials 2017 june.musadoto
 
Divide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docx
Divide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docxDivide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docx
Divide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docxjacksnathalie
 
MATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdfMATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdfahmed8651
 
SPL 2 | Algorithms, Pseudo-code, and Flowchart
SPL 2 | Algorithms, Pseudo-code, and FlowchartSPL 2 | Algorithms, Pseudo-code, and Flowchart
SPL 2 | Algorithms, Pseudo-code, and FlowchartMohammad Imam Hossain
 
M166Calculus” ProjectDue Wednesday, December 9, 2015PROJ.docx
M166Calculus” ProjectDue Wednesday, December 9, 2015PROJ.docxM166Calculus” ProjectDue Wednesday, December 9, 2015PROJ.docx
M166Calculus” ProjectDue Wednesday, December 9, 2015PROJ.docxinfantsuk
 
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docxMATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docxandreecapon
 
1672734902268_Slice based testing.pptx
1672734902268_Slice based testing.pptx1672734902268_Slice based testing.pptx
1672734902268_Slice based testing.pptxMirzaHammad12
 
Workshop03.docx lap trinh C cho người mới bắt đầu
Workshop03.docx  lap trinh C cho người mới bắt đầuWorkshop03.docx  lap trinh C cho người mới bắt đầu
Workshop03.docx lap trinh C cho người mới bắt đầulinhtran111111111111
 
Octave - Prototyping Machine Learning Algorithms
Octave - Prototyping Machine Learning AlgorithmsOctave - Prototyping Machine Learning Algorithms
Octave - Prototyping Machine Learning AlgorithmsCraig Trim
 

Ähnlich wie Solution of matlab chapter 6 (20)

BS LAB Manual (1).pdf
BS LAB Manual  (1).pdfBS LAB Manual  (1).pdf
BS LAB Manual (1).pdf
 
Name _______________________________ Class time __________.docx
Name _______________________________    Class time __________.docxName _______________________________    Class time __________.docx
Name _______________________________ Class time __________.docx
 
Matlab1
Matlab1Matlab1
Matlab1
 
Es272 ch1
Es272 ch1Es272 ch1
Es272 ch1
 
Matrix Multiplication(An example of concurrent programming)
Matrix Multiplication(An example of concurrent programming)Matrix Multiplication(An example of concurrent programming)
Matrix Multiplication(An example of concurrent programming)
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentation
 
Sample Exam Questions on Python for revision
Sample Exam Questions on Python for revisionSample Exam Questions on Python for revision
Sample Exam Questions on Python for revision
 
Matlab solved tutorials 2017 june.
Matlab solved tutorials  2017 june.Matlab solved tutorials  2017 june.
Matlab solved tutorials 2017 june.
 
Divide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docx
Divide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docxDivide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docx
Divide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docx
 
MATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdfMATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdf
 
C lab-programs
C lab-programsC lab-programs
C lab-programs
 
3.pdf
3.pdf3.pdf
3.pdf
 
SPL 2 | Algorithms, Pseudo-code, and Flowchart
SPL 2 | Algorithms, Pseudo-code, and FlowchartSPL 2 | Algorithms, Pseudo-code, and Flowchart
SPL 2 | Algorithms, Pseudo-code, and Flowchart
 
M166Calculus” ProjectDue Wednesday, December 9, 2015PROJ.docx
M166Calculus” ProjectDue Wednesday, December 9, 2015PROJ.docxM166Calculus” ProjectDue Wednesday, December 9, 2015PROJ.docx
M166Calculus” ProjectDue Wednesday, December 9, 2015PROJ.docx
 
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docxMATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
 
Taller parcial 2
Taller parcial 2Taller parcial 2
Taller parcial 2
 
1672734902268_Slice based testing.pptx
1672734902268_Slice based testing.pptx1672734902268_Slice based testing.pptx
1672734902268_Slice based testing.pptx
 
Workshop03.docx lap trinh C cho người mới bắt đầu
Workshop03.docx  lap trinh C cho người mới bắt đầuWorkshop03.docx  lap trinh C cho người mới bắt đầu
Workshop03.docx lap trinh C cho người mới bắt đầu
 
Octave - Prototyping Machine Learning Algorithms
Octave - Prototyping Machine Learning AlgorithmsOctave - Prototyping Machine Learning Algorithms
Octave - Prototyping Machine Learning Algorithms
 
R Programming Homework Help
R Programming Homework HelpR Programming Homework Help
R Programming Homework Help
 

Kürzlich hochgeladen

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 

Kürzlich hochgeladen (20)

Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 

Solution of matlab chapter 6

  • 1. 1 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 >>
  • 2. 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 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==~w ans = 1 1 0 0 1 1 1 >> % Part (b) >> w>=v ans = 1 1 0 1 1 0 1 >> % Part (c) >> v>~1*w ans = 0 1 1 0 1 1 1 >> % Part (d) >> v>-1*w ans = 0 1 1 1 1 0 1 >>
  • 4. 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 5 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 -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 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. 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 3 S = -24 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 vec- tor. 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 7 -8 -9 6 14 18 -6 7 4 -10 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 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 arbitrary length. Then, using a for loop the program eliminates all the negative ele- ments. The program displays the vector that was entered and the modified vector, 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 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. 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 11 vNew = Columns 1 through 13 17 6 7 15 13 5 16 2 20 10 3 1 9 Columns 14 through 17 3 14 14 11 8 elements were eliminated. 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
  • 9. 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. 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 dis- plays 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(j- 1)*factorial(i-j)); end end pt 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 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
  • 11. Chapter 6: Solved Problems 11 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 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. 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 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 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); end xi=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. (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 ψ ψ n 1 = ∞  = Fn ψ n 10 50 , , = n 0 = ∞ 
  • 13. Chapter 6: Solved Problems 13 ESpi=(32*S)^(1/3) Command Window: Enter a value for n 10 ESpi = 3.141642788603785 >> ed6_HW6_14 Enter a value for n 100 ESpi = 3.141592719141050 >> ed6_HW6_14 Enter a value for n 1000 ESpi = 3.141592653657139 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. 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 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 end end vFinal=vInitial fprintf('%.0f iterations were done.n',i-1) Command Window:
  • 15. 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 rearranges the 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, 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 -1.5000 13.4000 13.3000 -2.1000 4.6000 1.1000 5.0000 -6.1000 10.0000 0.2000 x = -6.1000 -2.1000 -1.5000 0.2000 1.1000
  • 16. 16 Chapter 6: Solved Problems 4.6000 5.0000 9.0000 10.0000 13.3000 13.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 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 cor- responds 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 4 5 5 12 13 6 8 10 7 24 25 8 15 17 9 12 15 9 40 41 a2 b2 + c2 =
  • 17. 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 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 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 end end Command Window: n =
  • 18. 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 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 end SafePrimeNum 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. 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 pro- gram 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:
  • 21. 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. 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 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 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. 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: 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). 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 An',G(i)) elseif G(i) > Av+0.5*S & G(i) < Av+1.3*S fprintf('%3i%% Letter grade Bn',G(i)) elseif G(i) > Av-0.5*S & G(i) < Av+0.5*S fprintf('%3i%% Letter grade Cn',G(i)) elseif G(i) > Av-1.3*S & G(i) < Av-0.5*S fprintf('%3i%% Letter grade Dn',G(i)) elseif G(i) < Av-1.3*S fprintf('%3i%% Letter grade Fn',G(i)) end Score (%) Letter grade A B Score (%) Letter grade C D Score (%) Letter grade F
  • 25. 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. 26 Chapter 6: Solved Problems 25. The Taylor series expansion for ax is: 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 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; 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 6.3 Enter a value for x 1.7 n 0 = ∞ 
  • 27. 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 such that the sum of all the integers 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 1 2 3 … n + + + +
  • 28. 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 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; 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 29 Enter age: 19 Enter resting heart rate: 64 Enter fitness level (low, medium, or high): medium THR = 147 (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 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.). 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: BMI Classification Below 18.5 Underweight 18.5 to 24.9 Normal 25 to 29.9 Overweight 30 and above Obese
  • 30. 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 you as underweightnn',BMI) elseif BMI<25 fprintf('nYour BMI value is %.1f, which classifies you as normalnn',BMI) elseif BMI<30 fprintf('nYour BMI value is %.1f, which classifies you as overweightnn',BMI) else fprintf('nYour BMI value is %.1f, which classifies you as obesenn',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 >>
  • 31. Chapter 6: Solved Problems 31 29. Write a program in a script file that calculates the cost of renting a car according to the following price schedule: 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 Duration of rent Sedan SUV Daily rate Free miles (per day) Cost of Additional mile Daily rate Free miles (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. 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.2fn',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
  • 33. Chapter 6: Solved Problems 33 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 >>
  • 34. 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 dis- plays 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 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. For example, 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, clc AmToPy=randi(5000)/100; fprintf('The amount to be paid is: $%5.2fn',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 billsn',R(1)) fprintf('%2.0f $10 billsn',R(2)) fprintf('%2.0f $5 billsn',R(3)) fprintf('%2.0f $1 billsn',R(4)) fprintf('%2.0f quartersn',R(5)) fprintf('%2.0f dimesn',R(6))
  • 35. Chapter 6: Solved Problems 35 fprintf('%2.0f nickelsn',R(7)) fprintf('%2.0f centsn',R(8)) end Command Window: The amount to be paid is: $13.93 Please enter payment in dollars (1, 5, 10, 20 or 50) 20 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) 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) 50 The change is: 0 $20 bills 0 $10 bills 1 $5 bills 4 $1 bills 3 quarters 2 dimes 0 nickels 3 cents >>
  • 36. 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, 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)') 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
  • 37. Chapter 6: Solved Problems 37 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(-
  • 38. 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 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 a third, 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 the program use 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) (b) (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 %gn',P,QRP) Command Window: Enter a number for calculating its cubic root: 800 the qubic root of 800 is 9.28318 Enter a number for calculating its cubic root: 59071 the qubic root of 59071 is 38.9456 Enter a number for calculating its cubic root: -31.55 the qubic root of -31.55 is -3.15985 P 3 x1 x2 x3 xi 1 + xi x1 P = 800 3 59071 3
  • 40. 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;
  • 41. 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; end if error disp('ERROR current or new units are typed incorrectly.') else fprintf('A= %g %sn',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 >>
  • 42. 42 Chapter 6: Solved Problems 34. In a one-dimensional random walk, the position x of a walker is computed by: 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 . 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 >> xj xj s + = B 10 =
  • 43. Chapter 6: Solved Problems 43 35. The Sierpinski triangle can be implemented in MATLAB by plotting points iteratively 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 then plots y versus x as individual points (use plot(x,y,‘^’)). Start with and . 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 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. 44 Chapter 6: Solved Problems Figure 10 iterations: Figure 100 iterations: Figure 1000 iterations:
  • 45. Chapter 6: Solved Problems 45 Figure 10,000 iterations:
  • 46. 46 Chapter 6: Solved Problems 36. The roots of a cubic equation can be calculated using 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, 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 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; 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;
  • 47. Chapter 6: Solved Problems 47 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.
  • 48. 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 home- work 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. 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, 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: % in',Grade)
  • 49. 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) 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 >>
  • 50. 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 num- bers (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 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, 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 >>
  • 51. Chapter 6: Solved Problems 51 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 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 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');
  • 52. 52 Chapter 6: Solved Problems Figure: