1. The following statements are intended to alert a user to dangerously high oral thermometer readings (values are in degrees Fahrenheit). Are they correct or incorrect? If they are incorrect, explain why and correct them.
if temp < 97.5
disp('Temperature below normal');
elseif temp > 97.5
disp('Temperature normal');
elseif temp > 99.5
disp('Temperature slightly high');
elseif temp > 103.0
disp('Temperature dangerously high');
end
Solution
This program executed without error, but there is a logical issue. When temperature is above 97.5 then it always goes into the second block, and rest of the conditions are not going to execute. So even if the temperature is danger then also it shows that the temperature is normal.
if temp < 97.5
disp('Temperature below normal');
elseif temp >= 97.5
if temp >= 103.0
disp('Temperature dangerously high');
elseif temp >= 99.5
disp('Temperature slightly high');
else
disp('Temperature normal');
end
end
2. Write a MATLAB program to evaluate the function:
y(x)=ln 1/(1 –x)
for any user-specified value of x, where x is a number <1.0 (note that ln is the natural logarithm, the logarithm to the base e). Use an if structure to verify that the value passed to the program is legal. If the value of x is legal, calculate y(x). If not, write a suitable error message and quit.
Solution
clc;
clear all;
close all;
x = input('Enter Value For X ');
if x >= 1.0
disp('Illegal Value For X!!');
return
end
yx = log(1/(1-x));
disp(['y(x) = ',num2str(yx)]);
3. Examine the following MATLAB statements. Are they correct or incorrect? If they are correct, what do they output? If they are incorrect, what is wrong with them?
a.)
if volts > 125
disp('WARNING: High voltage on line.');
if volts < 105
disp('WARNING: Low voltage on line.');
else
disp('Line voltage is within tolerances.');
end
Solution
This program gives error, because inside inner if statement end keyword is missing, so that the program execution is aborted.
b.)
color = 'yellow';
switch ( color )
case 'red',
disp('Stop now!');
case 'yellow',
disp('Prepare to stop.');
case 'green',
disp('Proceed through intersection.');
otherwise,
disp('Illegal color encountered.');
end
Output
Prepare to stop.
Solution
This program runs perfectly, and gives output ‘Prepare to stop.’, because the value of color is yellow, which match with the case yellow.
c.)
if temperature > 37
disp('Human body temperature exceeded.');
elseif temperature > 100
disp('Boiling point of water exceeded.');
end
Output
Enter Temperature 102
Human body temperature exceeded.
Solution
This program executed without error, but when value of temperature is less than 37 then there is no message is printed, and when temperature is greater than 100 then also first if statement is executed.