0% found this document useful (0 votes)
391 views

Chapter 3: Selection Statements Exercises

This document contains 13 exercises involving the use of selection statements and conditional logic in MATLAB scripts and functions. The exercises cover topics like prompting users for input, comparing values, writing conditional print statements, and creating and manipulating vectors based on input values and conditions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
391 views

Chapter 3: Selection Statements Exercises

This document contains 13 exercises involving the use of selection statements and conditional logic in MATLAB scripts and functions. The exercises cover topics like prompting users for input, comparing values, writing conditional print statements, and creating and manipulating vectors based on input values and conditions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Chapter 3: Selection Statements

 
Exercises 
 
1) What would be the result of the following expressions? 
'b' >= 'c' – 1 1

3 == 2 + 1 1

(3 == 2) + 1 1

xor(5 < 6, 8 > 4) 0


 
2) Write a script that tests whether the user can follow instructions.  It prompts the 
user to enter an ‘x’.  If the user enters anything other than an ‘x’, it prints an error 
message – otherwise, the script does nothing. 
 
    Ch3Ex2.m 
% Can the user follow instructions??

inx = input('Enter an x: ', 's');


if inx ~= 'x'
fprintf('That was no x!\n')
end
 
3) Write a function nexthour that receives one integer argument, which is an hour of 
the day, and returns the next hour.  This assumes a 12‐hour clock; so, for example, 
the next hour after 12 would be 1.  Here are two examples of calling this function. 
>> fprintf('The next hour will be %d.\n',nexthour(3))
The next hour will be 4.
>> fprintf('The next hour will be %d.\n',nexthour(12))
The next hour will be 1.
 
     nexthour.m 
function outhour = nexthour(currenthour)
% Receives an integer hour of the day and
% returns the next integer hour
% Format of call: nexthour(hour of day)
% Returns the next integer hour

outhour = currenthour + 1;
if outhour == 13
outhour = 1;
end
end
 
 
4) Write a script to calculate the volume of a pyramid, which is 1/3 * base * height,
where the base is length * width. Prompt the user to enter values for the length, width,
and height, and then calculate the volume of the pyramid. When the user enters each
value, he or she will then also be prompted for either ‘i’ for inches or ‘c’ for centimeters.
(Note 2.54 cm = 1 inch). The script should print the volume in cubic inches with three
decimal places. As an example, the output format will be:

This program will calculate the volume of a pyramid.


Enter the length of the base: 50
Is that i or c? i
Enter the width of the base: 6
Is that i or c? c
Enter the height: 4
Is that i or c? i

The volume of the pyramid is xxx.xxx cubic inches.


   
     Ch3Ex4.m 
%Calculate the volume of a pyramid

% Prompt the user for the length, width, and height in


% either inches or centimeters (inches is assumed and
will
% be the default)

disp('This script will calculate the volume of a


pyramid.')
len = input('Enter the length of the base: ');
lenunit = input('Is that i or c? ','s');
if lenunit == 'c'
len = len/2.54;
end
wid = input('Enter the width of the base: ');
widunit = input('Is that i or c? ','s');
if widunit == 'c'
wid = wid/2.54;
end
ht = input('Enter the height: ');
htunit = input('Is that i or c? ','s');
if htunit == 'c'
ht = ht/2.54;
end

vol = 1/3 * len * wid * ht;


fprintf('\nThe volume of the pyramid is ')
fprintf('%.3f cubic inches.\n',vol)
 
5) Write a script to prompt the user for a character, and then print ether that it is a 
letter of the alphabet or that it is not. 
 
Ch3Ex5.m
%Prompt for a character and print whether it is
% a letter of the alphabet or not

let = input('Enter a character: ', 's');


if (let >= 'a' && let <= 'z') || ...
(let >= 'A' && let <= 'Z')
fprintf('%c is a letter\n', let)
else
fprintf('%c is not a letter\n', let)
end
 
6) Write a script that will prompt the user for a numerator and a denominator for a 
fraction.  If the denominator is 0, it will print an error message saying that division 
by 0 is not possible.  If the denominator is not 0, it will print the result of the 
fraction. 
 
Ch3Ex6.m
%Prompt the user for a numerator and denominator
% and print the fraction or an error message

num = input('Enter the numerator: ');


den = input('Enter the denominator: ');

if den == 0
fprintf('Division by 0 not possible\n')
else
fprintf('The fraction is %.2f\n', num/den)
end
 
2

7) The eccentricity of an ellipse is defined as 
b
1  
a
 
where a is the semimajor axis and b is the semiminor axis of the ellipse.  A script 
prompts the user for the values of a and b. Since division by 0 is not possible, the 
script prints an error message if the value of a is 0 (it ignores any other errors, 
however).  If a is not 0, the script calls a function to calculate and return the 
eccentricity, and then the script prints the result.  Write the script and the function. 
 
Ch3Ex7.m
% Prompts the user for the semimajor and semiminor axes of
% an ellipse and calculates and returns the eccentricity
% (if the semimajor axis ~=0)

a = input('Enter the semimajor axis: ');


b = input('Enter the semiminor axis: ');
if a == 0
disp('Error: semimajor cannot be 0')
else
eccentricity = EllEcc(a,b);
fprintf('The eccentricity is %.2f\n', eccentricity)
end
 
EllEcc.m
function eccen = EllEcc(a,b)
% Calculates the eccentricity of an ellipse given
% the semimajor axis a and the semiminor axis b
% Format of call: EllEcc(a,b)
% Returns the eccentricity

eccen = sqrt(1- (b/a)^2);


end
 
8) The systolic and diastolic blood pressure readings are found when the heart is 
pumping and the heart is at rest, respectively.  A biomedical experiment is being 
conducted only on subjects whose blood pressure is optimal.  This is defined as a 
systolic blood pressure less than 120 and a diastolic blood pressure less than 80.  
Write a script that will prompt for the systolic and diastolic blood pressures of a 
person, and will print whether or not that person is a candidate for this experiment. 
 
Ch3Ex8.m 
% Checks blood pressures to determine whether or
% not a person is a candidate for an experiment

syst = input('Enter the systolic blood pressure: ');


diast = input('Enter the diastolic blood pressure: ');

if syst < 120 && diast < 80


disp('This person is a candidate.')
else
disp('This person is not suitable for the experiment.')
end
 
9) The continuity equation in fluid dynamics for steady fluid flow through a stream 
tube equates the product of the density, velocity, and area at two points that have 
varying cross‐sectional areas.  For incompressible flow, the densities are constant so 
A1
the equation is A1V1 = A2V2 .  If the areas and V1 are known,  V2 can be found as  V1 .  
A2
Therefore, whether the velocity at the second point increases or decreases depends 
on the areas at the two points.  Write a script that will prompt the user for the two 
areas in square feet, and will print whether the velocity at the second point will 
increase, decrease, or remain the same as at the first point. 
 
Ch3Ex9.m 
% Prints whether the velocity at a point in a stream tube
% will increase, decrease, or remain the same at a second
% point based on the cross-sectional areas of two points

a1 = input('Enter the area at point 1: ');


a2 = input('Enter the area at point 2: ');

if a1 > a2
disp('The velocity will increase')
elseif a1 < a2
disp('The velocity will decrease')
else
disp('The velocity will remain the same')
end
 
10) In chemistry, the pH of an aqueous solution is a measure of its acidity.  The pH 
scale ranges from 0 to 14, inclusive.  A solution with a pH of 7 is said to be neutral, a 
solution with a pH greater than 7 is basic, and a solution with a pH less than 7 is 
acidic.  Write a script that will prompt the user for the pH of a solution, and will 
print whether it is neutral, basic, or acidic.  If the user enters an invalid pH, an error 
message will be printed.   
 
Ch3Ex10.m 
% Prompts the user for the pH of a solution and prints
% whether it is basic, acidic, or neutral

ph = input('Enter the pH of the solution: ');


if ph >=0 && ph <= 14
if ph < 7
disp('It is acidic')
elseif ph == 7
disp('It is neutral')
elseif ph > 7
disp('It is basic')
end
else
disp('Error in pH!')
end
 
11) Write a function createvecMToN that will create and return a vector of integers 
from m to n (where m is the first input argument and n is the second), regardless of 
whether m is less than n or greater than n.  If m is equal to n, the “vector” will just be 
1 x 1 or a scalar.  
 
createvecMToN.m
function outvec = createvecMToN(m,n)
% Creates a vector of integers from m to n
% Format of call: createvecMToN(m,n)
% Returns vector of integers from m:n or m:-1:n

if m < n
outvec = m:n;
else
outvec = m:-1:n;
end
end
 
12) Write a function flipvec that will receive one input argument.  If the input 
argument is a row vector, the function will reverse the order and return a new row 
vector.  If the input argument is a column vector, the function will reverse the order 
and return a new column vector.  If the input argument is a matrix or a scalar, the  
function will return the input argument unchanged.   

flipvec.m
function out = flipvec(vec)
% Flips it if it's a vector, otherwise
% returns the input argument unchanged
% Format of call: flipvec(vec)
% Returns flipped vector or unchanged

[r c] = size(vec);

if r == 1 && c > 1
out = fliplr(vec);
elseif c == 1 && r > 1
out = flipud(vec);
else
out = vec;
end
end

13) In a script, the user is supposed to enter either a ‘y’ or ‘n’ in response to a 
prompt.  The user’s input is read into a character variable called “letter”.  The script 
will print “OK, continuing” if the user enters either a ‘y’ or ‘Y’ or it will print “OK, 
halting” if the user enters a ‘n’ or ‘N’ or “Error” if the user enters anything else.  Put 
this statement in the script first: 
letter = input('Enter your answer: ', 's');
Write the script using a single nested if­else statement (elseif clause is permitted).  
 
Ch3Ex13.m 
% Prompts the user for a 'y' or 'n' answer and responds
% accordingly, using an if-else statement

letter = input('Enter your answer: ', 's');

if letter == 'y' || letter == 'Y'


disp('OK, continuing')
elseif letter == 'n' || letter == 'N'
disp('OK, halting')
else
disp('Error')
end
 
14) Write the script from the previous exercise using a switch statement instead. 
 
Ch3Ex14.m 
% Prompts the user for a 'y' or 'n' answer and responds
% accordingly, using an if-else statement

letter = input('Enter your answer: ', 's');

switch letter
case {'y', 'Y'}
disp('OK, continuing')
case {'n', 'N'}
disp('OK, halting')
otherwise
disp('Error')
end
 
15) In aerodynamics, the Mach number is a critical quantity.  It is defined as the 
ratio of the speed of an object (e.g., an aircraft) to the speed of sound.  If the Mach 
number is less than 1, the flow is subsonic; if the Mach number is equal to 1, the flow 
is transonic; if the Mach number is greater than 1, the flow is supersonic.  Write a 
script that will prompt the user for the speed of an aircraft and the speed of sound at 
the aircraft’s current altitude and will print whether the condition is subsonic, 
transonic, or supersonic. 
 
Ch3Ex15.m 
% Prints whether the speed of an object is subsonic,
% transonic, or supersonic based on the Mach number

plane_speed = input('Enter the speed of the aircraft: ');


sound_speed = input('Enter the speed of sound: ');
mach = plane_speed/sound_speed;

if mach < 1
disp('Subsonic')
elseif mach == 1
disp('Transonic')
else
disp('Supersonic')
end
 
 
16) Write a script that will prompt the user for a temperature in degrees Celsius, 
and then an ‘F’ for Fahrenheit or ‘K’ for Kelvin.  The script will print the 
corresponding temperature in the scale specified by the user. For example, the 
output might look like this:   
Enter the temp in degrees C: 29.3
Do you want K or F? F
The temp in degrees F is 84.7
The format of the output should be exactly as specified above.  The conversions are: 
9
    F  C  32  
5
    K  C  273.15  
 
Ch3Ex16.m 
% Converts a temperature from C to F or K

cel = input('Enter the temp in degrees C: ');


fork = input('Do you want F or K? ', 's');

if fork == 'F' || fork == 'f'


fprintf('The temp in degrees F is %.1f\n', 9/5*cel+32)
else
fprintf('The temp in degrees K is %.1f\n', cel+273.15)
end
 
17) Write a script that will generate one random integer, and will print whether the 
random integer is an even or an odd number.  (Hint: an even number is divisible by 
2, whereas an odd number is not; so check the remainder after dividing by 2.) 
 
Ch3Ex17.m 
% Generates a random integer and prints whether it is even
or odd
ranInt = randi([1, 100]);

if rem(ranInt,2) == 0
fprintf('%d is even\n', ranInt)
else
fprintf('%d is odd\n', ranInt)
end
 
18) Write a function isdivby4 that will receive an integer input argument, and will 
return logical 1 for true if the input argument is divisible by 4, or logical false if it 
is not. 
 
isdivby4.m 
function out = isdivby4(inarg)
% Returns 1 for true if the input argument is
% divisible by 4 or 0 for false if not
% Format of call: isdivby4(input arg)
% Returns whether divisible by 4 or not

out = rem(inarg,4) == 0;
end
 
19) Write a function isint that will receive a number input argument innum, and will 
return 1 for true if this number is an integer, or 0 for false if not.  Use the fact that 
innum should be equal to int32(innum) if it is an integer.  Unfortunately, due to 
round‐off errors, it should be noted that it is possible to get logical 1 for true if the 
input argument is close to an integer.  Therefore the output may not be what you 
might expect, as shown here. 
>> isint(4)
ans =
1

>> isint(4.9999)
ans =
0

>> isint(4.9999999999999999999999999999)
ans =
1

isint.m
function out = isint(innum)
% Returns 1 for true if the argument is an integer
% Format of call: isint(number)
% Returns logical 1 iff number is an integer
out = innum == int32(innum);
end
 
20) A Pythagorean triple is a set of positive integers (a,b,c) such that a2 + b2 = c2.  
Write a function ispythag that will receive three positive integers (a, b, c in that 
order) and will return  logical 1 for true if they form a Pythagorean triple, or 0 for 
false if not. 
 
ispythag.m 
function out = ispythag(a,b,c)
% Determines whether a, b, c are a Pythagorean
% triple or not
% Format of call: ispythag(a,b,c)
% Returns logical 1 if a Pythagorean triple

out = a^2 + b^2 == c^2;


end
 
21) In fluid dynamics, the Reynolds number Re is a dimensionless number used to 
determine the nature of a fluid flow. For an internal flow (e.g., water flow through a 
pipe), the flow can be categorized as follows: 
 
Re ≤ 2300  Laminar Region 
2300 < Re ≤ 4000  Transition Region 
Re > 4000  Turbulent Region 
 
Write a script that will prompt the user for the Reynolds number of a flow and will 
print the region the flow is in. Here is an example of running the script: 

>> Reynolds
Enter a Reynolds number: 3500
The flow is in transition region

Ch3Ex21.m
% Prompts the user for the Reynolds number
% for an internal flow and prints
% whether it is laminar, turbulent, or in
% a transition region

Re = input('Enter a Reynolds number: ');

if Re <= 2300
disp('The flow is in laminar region')
elseif Re > 2300 && Re <= 4000
disp('The flow is in transition region')
else
disp('The flow is in turbulent region')
end

Would it be a good idea to write the selection statements using switch? Why or why 
not?  
 
No, because the Reynolds number could be a real number and the ranges are too 
large. 
dd
22) The area A of a rhombus is defined as A =  1 2 , where d1 and d2 are the lengths 
2
of the two diagonals.  Write a script rhomb that first prompts the user for the lengths 
of the two diagonals.  If either is a negative number or zero, the script prints an 
error message.  Otherwise, if they are both positive, it calls a function rhombarea to 
return the area of the rhombus, and prints the result.  Write the function, also!  The 
lengths of the diagonals, which you can assume are in inches, are passed to the 
rhombarea function.   
 
rhomb.m 
% Prompt the user for the two diagonals of a rhombus,
% call a function to calculate the area, and print it

d1 = input('Enter the first diagonal: ');


d2 = input('Enter the second diagonal: ');

if d1 <= 0 || d2 <= 0
disp('Error in diagonal')
else
rharea = rhombarea(d1,d2);
fprintf('The area of the rhombus is %.2f\n', rharea)
end

rhombarea.m
function rarea = rhombarea(d1,d2)
% Calculates the area of a rhombus given the
% lengths of the two diagonals
% Format of call: rhombarea(diag1, diag2)
% Returns the area of the rhombus

rarea = (d1*d2)/2;
end
 
 
Global temperature changes have resulted in new patterns of storms in many parts of 
the world.  Tracking wind speeds and a variety of categories of storms is important in 
understanding the ramifications of these temperature variations.  Programs that work 
with storm data will use selection statements to determine the severity of storms and 
also to make decisions based on the data. 
 
23) Whether a storm is a tropical depression, tropical storm, or hurricane is 
determined by the average sustained wind speed.  In miles per hour, a storm is a 
tropical depression if the winds are less than 38 mph.  It is a tropical storm if the 
winds are between 39 and 73 mph, and it is a hurricane if the wind speeds are >= 74 
mph.  Write a script that will prompt the user for the wind speed of the storm, and 
will print which type of storm it is. 
 
Ch3Ex23.m 
% Prints whether a storm is a tropical depression, tropical
% storm, or hurricane based on wind speed

wind = input('Enter the wind speed of the storm: ');

if wind < 38
disp('Tropical depression')
elseif wind >= 38 && wind < 73
disp('Tropical storm')
else
disp('Hurricane')
end
 
24) Hurricanes are categorized based on wind speeds.  The following table shows 
the Category number for hurricanes with varying wind ranges and what the storm 
surge is (in feet above normal).  
 
           Cat  Wind speed  Storm surge 
    1  74‐95    4‐5 
    2  96‐110    6‐8 
    3  111‐130  9‐12 
    4  131‐155  13‐18 
    5  >155    >18 
Write a script that will prompt the user for the wind speed, and will print the 
hurricane category number and the typical storm surge. 
 
Ch3Ex24.m 
% Prints the category number and storm surge for
% a hurricane based on the wind speed

wind = input('Enter the wind speed: ');

if wind >= 74 && wind <=95


fprintf('Category 1; typical storm surge 4-5 ft\n')
elseif wind > 95 && wind <= 110
fprintf('Category 2; typical storm surge 6-8 ft\n')
elseif wind > 110 && wind <= 130
fprintf('Category 3; typical storm surge 9-12 ft\n')
elseif wind > 130 && wind <= 155
fprintf('Category 4; typical storm surge 13-18 ft\n')
elseif wind > 155
fprintf('Category 5; typical storm surge > 18 ft\n')
else
fprintf('Not a hurricane\n')
end
 
25) The Beaufort Wind Scale is used to characterize the strength of winds.  The scale 
uses integer values and goes from a force of 0, which is no wind, up to 12, which is a 
hurricane.  The following script first generates a random force value.  Then, it prints 
a message regarding what type of wind that force represents, using a switch 
statement.  You are to re‐write this switch statement as one nested if­else 
statement that accomplishes exactly the same thing.  You may use else and/or elseif 
clauses. 
 
ranforce = round(rand*12);

switch ranforce
case 0
disp('There is no wind')
case {1,2,3,4,5,6}
disp('There is a breeze')
case {7,8,9}
disp('This is a gale')
case {10,11}
disp('It is a storm')
case 12
disp('Hello, Hurricane!')
end
 
Ch3Ex25.m 
if ranforce == 0
disp('There is no wind')
elseif ranforce >= 1 && ranforce <= 6
disp('There is a breeze')
elseif ranforce >= 7 && ranforce <= 9
disp('This is a gale')
elseif ranforce == 10 || ranforce == 11
disp('It is a storm')
else
disp('Hello, Hurricane!')
end
 
 
26) Clouds are generally classified as high, middle, or low level.  The height of the 
cloud is the determining factor, but the ranges vary depending on the temperature.  
For example, in tropical regions the classifications may be based on the following 
height ranges (given in feet): 
  low    0‐6500 
  middle   6500‐20000 
  high    > 20000 
Write a script that will prompt the user for the height of the cloud in feet, and print 
the classification. 
 
Ch3Ex26.m 
% Prints cloud classification

cloudHt = input('Enter the height of the cloud in feet: ');

if cloudHt > 0 && cloudHt <=6500


disp('This is a low cloud')
elseif cloudHt > 6500 && cloudHt <= 20000
disp('This is a middle cloud')
elseif cloudHt > 20000
disp('This is a high cloud')
else
disp('Error: how could this be a cloud?')
end

 
27) Rewrite the following switch statement as one nested if­else statement (elseif 
clauses may be used).  Assume that there is a variable letter and that it has been 
initialized.

switch letter
case 'x'
disp('Hello')
case {'y', 'Y'}
disp('Yes')
case 'Q'
disp('Quit')
otherwise
disp('Error')
end
 
Ch3Ex27.m 
letter = char(randi([97,122]));
if letter == 'x'
disp('Hello')
elseif letter == 'y' || letter == 'Y'
disp('Yes')
elseif letter == 'Q'
disp('Quit')
else
disp('Error')
end
 
28) Rewrite the following nested if­else statement as a switch statement that 
accomplishes exactly the same thing.  Assume that num is an integer variable that 
has been initialized, and that there are functions f1, f2, f3, and f4.  Do not use any if 
or if­else statements in the actions in the switch statement, only calls to the four 
functions.

if num < -2 || num > 4


f1(num)
else
if num <= 2
if num >= 0
f2(num)
else
f3(num)
end
else
f4(num)
end
end
 
Ch3Ex28.m 
switch num
case {-2, -1}
f3(num)
case {0, 1, 2}
f2(num)
case {3, 4}
f4(num)
otherwise
f1(num)
end
 
29) Write a script areaMenu that will print a list consisting of “cylinder”, “circle”, and 
“rectangle”.  It prompts the user to choose one, and then prompts the user for the 
appropriate quantities (e.g., the radius of the circle) and then prints its area.  If the 
user enters an invalid choice, the script simply prints an error message.  The script 
should use a nested if­else statement to accomplish this.  Here are two examples of 
running it (units are assumed to be inches). 
>> areaMenu
Menu
1. Cylinder
2. Circle
3. Rectangle
Please choose one: 2
Enter the radius of the circle: 4.1
The area is 52.81

>> areaMenu
Menu
1. Cylinder
2. Circle
3. Rectangle
Please choose one: 3
Enter the length: 4
Enter the width: 6
The area is 24.00
 
areaMenu.m 
% Prints a menu and calculates area of user's choice

disp('Menu')
disp('1. Cylinder')
disp('2. Circle')
disp('3. Rectangle')
sh = input('Please choose one: ');
if sh == 1
rad = input('Enter the radius of the cylinder: ');
ht = input('Enter the height of the cylinder: ');
fprintf('The surface area is %.2f\n', 2*pi*rad*ht)
elseif sh == 2
rad = input('Enter the radius of the circle: ');
fprintf('The area is %.2f\n', pi*rad*rad)
elseif sh == 3
len = input('Enter the length: ');
wid = input('Enter the width: ');
fprintf('The area is %.2f\n', len*wid)
else
disp('Error! Not a valid choice.')
end
 
30) Modify the areaMenu script to use a switch statement to decide which area to 
calculate. 
 
areaMenuSwitch.m 
% Prints a menu and calculates area of user's choice

disp('Menu')
disp('1. Cylinder')
disp('2. Circle')
disp('3. Rectangle')
sh = input('Please choose one: ');
switch sh
case 1
rad = input('Enter the radius of the cylinder: ');
ht = input('Enter the height of the cylinder: ');
fprintf('The surface area is %.2f\n', 2*pi*rad*ht)
case 2
rad = input('Enter the radius of the circle: ');
fprintf('The area is %.2f\n', pi*rad*rad)
case 3
len = input('Enter the length: ');
wid = input('Enter the width: ');
fprintf('The area is %.2f\n', len*wid)
otherwise
disp('Error! Not a valid choice.')
end
 
31) Modify the areaMenu script (either version) to use the built‐in menu function 
instead of printing the menu choices. 
 
Ch3Ex31.m 
% Prints a menu and calculates area of user's choice

sh = menu('Please choose one:','Cylinder', 'Circle', 'Rectangle');


switch sh
case 1
rad = input('Enter the radius of the cylinder: ');
ht = input('Enter the height of the cylinder: ');
fprintf('The surface area is %.2f\n', 2*pi*rad*ht)
case 2
rad = input('Enter the radius of the circle: ');
fprintf('The area is %.2f\n', pi*rad*rad)
case 3
len = input('Enter the length: ');
wid = input('Enter the width: ');
fprintf('The area is %.2f\n', len*wid)
otherwise
disp('Error! Not a valid choice.')
end
 
 
32) Write a script that prompts the user for a value of a variable x.  Then, it uses the 
menu function to present choices between  ‘sin(x)’, ‘cos(x)’, and ‘tan(x)’.  The script 
will print whichever function of x the user chooses.  Use an if­else statement to 
accomplish this. 
 
Ch3Ex32.m 
% Prints either sin, cos, or tan of x
% uses the menu function to choose

x = input('Enter a value for x: ');


choice = menu('Choose a function','sin','cos','tan');
if choice == 1
fprintf('sin(%.1f) is %.1f\n', x, sin(x))
elseif choice == 2
fprintf('cos(%.1f) is %.1f\n', x, cos(x))
elseif choice == 3
fprintf('tan(%.1f) is %.1f\n', x, tan(x))
end
 
33) Modify the above script to use a switch statement instead.  
 
Ch3Ex33.m 
% Prints either sin, cos, or tan of x
% uses the menu function to choose

x = input('Enter a value for x: ');


choice = menu('Choose a function','sin','cos','tan');
switch choice
case 1
fprintf('sin(%.1f) is %.1f\n', x, sin(x))
case 2
fprintf('cos(%.1f) is %.1f\n', x, cos(x))
case 3
fprintf('tan(%.1f) is %.1f\n', x, tan(x))
end
 
34) Write a function that will receive one number as an input argument.  It will use 
the menu function that will display ‘Choose a function’ and will have buttons 
labeled ‘ceil’, ‘round’, and ‘sign’.  Using a switch statement, the function will then 
calculate and return the requested function (e.g., if ‘round’ is chosen, the function 
will return the rounded value of the input argument). 
 
choosefn.m 
function outarg = choosefn(inarg)
% Chooses whether to use ceil, round, or sign
% on the input argument
% Format of call: choosefn(input arg)
% Returns ceil(input arg) or round or sign

choice = menu('Choose a function','ceil','round','sign');


switch choice
case 1
outarg = ceil(inarg);
case 2
outarg = round(inarg);
case 3
outarg = sign(inarg);
end
end
 
35) Modify the function in Question 34 to use a nested if­else statement instead. 
 
choosefn2.m 
function outarg = choosefn2(inarg)
% Chooses whether to use ceil, round, or sign
% on the input argument
% Format of call: choosefn(input arg)
% Returns ceil(input arg) or round or sign

choice = menu('Choose a function','ceil','round','sign');


if choice == 1
outarg = ceil(inarg);
elseif choice == 2
outarg = round(inarg);
elseif choice == 3
outarg = sign(inarg);
end
end
 
36) Simplify this statement: 
 
if num < 0
num = abs(num);
else
num = num;
end
 
if num < 0
num = abs(num);
end
% or just:

num = abs(num);
   
37) Simplify this statement: 
 
if val >= 4
disp('OK')
elseif val < 4
disp('smaller')
end

if val >= 4
disp('OK')
else
disp('smaller')
end

You might also like