In: Mechanical Engineering
Mat Lab Question
Mat Lab Question:
%% Q1 (60%)
% Follow the steps below to complete this question.
%
% Step 1: (40%)
% Create a function to perform calculations: +, -, *, or /
% 1.1 The function name should be calc and saved in its file.
% 1.2 The function has three parameters a, b, and op. The op is
an
% operator.
% 1.3 The function returns variable r for the calculation
result.
% 1.4 The function should provide the following help text:
% "The calc is a simple calculator. It has three parameters.
% The first two parameters are numerical operands, and the third
one
% is an operator +, -, *, or / "
% 1.5 Use the if conditional statement in the funciton to check the
operator op
% and compute accordingly.
% Note: Example about the syntax to check a single character: if(op
== '+')
% Note: You can test the calc function in the Command Window using
the syntax:
% >> calc(5, 3, '+')
% You can display the help text:
% >> help calc
%
% You can check if a division is divided by 0, but this is not
required. Hint: use Inf or NaN
%
%% Q2 (15%)
% This question is similar to the requirement in Step 1 of Q1,
except the
% following:
% Function name: calc_switch.m
% Here you want to use the switch statement instead of the if
statement to check the operator.
% You are not required to do Steps 2-4 in Q1. But you can test this
function in the same way.
Answer to question 1:
CODE:
function r=calc(a,b,op)
display('The calc is a simple calculator. It has three
parameters.');
display('The first two parameters are numerical operands and the
third one is an operator +, -, *, /');
if op=='+'
r=a+b;
else
if op=='-'
r=a-b;
else
if op=='*'
r=a*b;
else if op=='/'
r=a/b;
end
end
end
end
OUTPUT 1:
>> calc(5,3,'+')
The calc is a simple calculator. It has three parameters.
The first two parameters are numerical operands and the third one
is an operator +, -, *, /
ans =
8
OUTPUT 2:
>> calc(3,0,'/')
The calc is a simple calculator. It has three parameters.
The first two parameters are numerical operands and the third one
is an operator +, -, *, /
ans =
Inf
Answer to question 2:
CODE:
function r=calc_switch(a,b,op)
display('The calc_switch is a simple calculator. It has three
parameters.');
display('The first two parameters are numerical operands and the
third one is an operator +, -, *, /');
switch op
case '+'
r=a+b;
case '-'
r=a-b;
case '*'
r=a*b;
case '/'
r=a/b;
end
OUTPUT :
calc_switch(5,3,'+')
The calc_switch is a simple calculator. It has three
parameters.
The first two parameters are numerical operands and the third one
is an operator +, -, *, /
ans =
8