Practice Problems in Userdefined Function and If Statement SET 2
Practice Problems in Userdefined Function and If Statement SET 2
a) Write a MATLAB user defined function using if statements to compute the total
reward for one salesperson based on two inputs, number of residential phone lines
sold and business phone lines sold.
Answer:
Answer:
R=input('enter R=');
B=input('enter B=');
reward=sales(R,B);
if reward >8500
disp('reward = 8500');
else
disp(['reward= ',num2str(reward)]);
end
(or)
R=input('enter R=');
B=input('enter B=');
reward=sales(R,B);
if R||B<0
disp('invalid number');
elseif reward >8500
disp('reward = 8500');
else
disp(['reward= ',num2str(reward)]);
end
𝑏 2
√1 − ( )
𝑎
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. As division by 0 is not
possible, the script prints an error message if the value of a is 0. If a is not 0, the
script calls a function to calculate and returns the eccentricity, and then the script
prints the result. Write the script and the function.
Answers:
Main program:
a=input(‘enter the value of a’);
b=input(‘enter the value of b’);
if a==0;
disp(‘Error’)
else
E = elp(a,b);
disp(E)
User Defined Function:
function E = elp(a,b)
E=sqrt(1-(b/a)^2);
End
else
disp('The given year is not a leap year’)
end
(or)
else
disp ( ['The year ',num2str(year),' is not aleap year'] );
end
5. 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.
Answers:
if operator=='+'
C=A+B;
elseif operator=='-'
C=A-B;
elseif operator=='*'
C=A*B;
elseif operator=='/'
C=A/B;
else
disp('invalid operator')
end
disp(['The value of C=',num2str(C)]);
if X=='a'||X=='e'||X=='i'||X=='o'||X=='u'
disp('X is a vowel')
elseif X=='0'||X=='1'||X=='2'||X=='3'||X=='4'||X=='5'||X=='6'
||X=='7'||X=='8'||X=='9'
disp('X is a Number')
else
disp('X is Consonant');
end