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

Lab Assignment 8

Uploaded by

kunalankoliya210
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Lab Assignment 8

Uploaded by

kunalankoliya210
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Lab 8

Aim:
Programming experiment based on if ... end" structure, relational and logical operators, ”for ...
end" loop, ”while ... end" loop.

Prerequisite:
MATLAB basics

Learning Outcomes:
Students will learn to create functions with if ... end" structure, relational and logical operators,
”for ... end" loop, ”while ... end" loop.

Theory:
If Statement
The if statement chooses whether another statement, or group of statements, is executed or
not. The general form of the if statement is:
if condition
action
end

A condition is a relational expression that is conceptually, or logically, true or false. The


action is a statement, or a group of statements, that will be executed if the condition is true.

If else statement
The if statement chooses whether or not an action is executed. Choosing between two actions,
or choosing from among several actions, is accomplished using if-else, nested if-else, and
switch statements. The if-else statement is used to choose between two statements, or sets of
statements.
The general form is:
if condition
actionl
else
action2
end
First, the condition is evaluated.

Nested if else statement


The if-else statement is used to choose between two actions. To choose from more than two
actions the if-else statements can be nested, meaning one statement inside of another. For
example, consider implementing the following continuous mathematical function y= f(x):
y=l if x<-1
y = x2 if - 1 <= x <= 2
y = 4 if x > 2
The value of y is based on the value of x, which could be in one of three possible ranges.

Switch Case Statement


A switch statement can often be used in place of a nested if-else or an if statement with many
elseif clauses. Switch statements are used when an expression is tested to see whether it is
equal to one of several possible values. The general form of the switch statement is:
switch switch_expression
case caseexpl
actionl
case caseexp2
action2
case caseexp3
action3
% etc : there can be many of these
otherwise
actionn
end
The switch statement starts with the reserved word switch, and ends with the reserved word
end.

Tasks :
1. 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.
2. 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; and 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.
3. 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].
4. 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.
5. Write a function eqfn that will calculate f(x) = x^2 + 1/x for all elements of x. Since x
division by 0 is not possible, if any element in x is zero, the function will instead
return a flag of -99.

PART B

(PART B : TO BE COMPLETED BY STUDENTS)

(Students must submit the soft copy as per following segments within two hours of the
practical slot. The soft copy must be uploaded on the Blackboard or emailed to the
concerned lab in charge faculties at the end of the practical in case the there is no Black
board access available)

Roll No.: A104 Name: Khushi Ankoliya

Class: B. Tech. CSBS Batch: 1

Date of Experiment: 30/09/2024 Date of submission: 30/09/2024

Grade: Time of Submission: 1:00 pm

Date of Grading

B.1 Script / Command / Code


Question Input Output
%% Question 1 %%
1 windSpeed = input('Enter the wind speed of the
Output-1:
Enter the wind speed of the storm in mph:
storm in mph: '); 30
This is a tropical depression.
if windSpeed < 38
fprintf('This is a tropical depression.\n');
Output-2:
elseif windSpeed >= 39 && windSpeed <= 73
fprintf('This is a tropical storm.\n'); Enter the wind speed of the storm in mph:
elseif windSpeed >= 74 54
fprintf('This is a hurricane.\n'); This is a tropical storm.
else
fprintf('Invalid wind speed.\n'); Output 3:
end Enter the wind speed of the storm in mph:
80
This is a hurricane.
2 %% Question 2 %%
Enter the speed of the aircraft (in mph):
speedObject = input('Enter the speed of the 5
aircraft (in mph): '); Enter the speed of sound at current
speedSound = input('Enter the speed of sound at altitude (in mph):
current altitude (in mph): '); 340
The flow is subsonic.
machNumber = speedObject / speedSound;

if machNumber < 1
fprintf('The flow is subsonic.\n');
elseif machNumber == 1
fprintf('The flow is transonic.\n');
else
fprintf('The flow is supersonic.\n');
end
3 %% Question 3 %% Enter your answer (y/n):
y
letter = input('Enter your answer (y/n): ', 's'); OK, continuing

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


fprintf('OK, continuing\n');
elseif letter == 'n' || letter == 'N' Enter your answer (y/n):
fprintf('OK, halting\n'); n
else
OK, halting
fprintf('Error\n');
end
%% Question 4 %%
4
Flipvec file: Enter a vector (row or column):
[1, 2, 3, 4, 5]
function result = flipvec(inputArg) Original Vector:
% Check if the input is a row vector 1 2 3 4 5
if isrow(inputArg)
result = inputArg(end:-1:1); % Reverse row Flipped Vector:
vector 5 4 3 2 1
% Check if the input is a column vector
elseif iscolumn(inputArg)
result = inputArg(end:-1:1); % Reverse
column vector
% If input is not a vector (i.e., matrix or scalar)
else
result = inputArg; % Return the input
unchanged
end
end

main file:

% Prompt the user to enter a vector


inputVec = input('Enter a vector (row or column):
');

% Call the flipvec function and store the result


resultVec = flipvec(inputVec);

% Display the original and flipped vectors


disp('Original Vector:');
disp(inputVec);

disp('Flipped Vector:');
disp(resultVec);

Main file
5
% Prompt the user to enter a vector of values Enter a vector of values for x:
x = input('Enter a vector of values for x: '); [1,2,3,4]
Input vector x:
% Call the eqfn function to calculate f(x)
1 2 3 4
result = eqfn(x);

% Display the original input and the result Resulting vector f(x):
disp('Input vector x:'); 2.0000 4.5000 9.3333 16.2500
disp(x);
% Check if the result indicates an error (-99) or a
valid output
if result == -99
disp('Error: Division by zero occurred in the
input vector.');
else
disp('Resulting vector f(x):');
disp(result);
end

function file:

function result = eqfn(x)


% Check if any element in the input vector x is
zero
if any(x == 0)
% Return -99 if division by zero would occur
result = -99;
else
% Calculate f(x) = x^2 + 1/x for each
element in x
result = x.^2 + 1 ./ x;
end
end

B.2 Observations and learning:


Throughout the tasks, the key learning points were in understanding how MATLAB handles
various conditions and how to structure functions and scripts efficiently. We explored
decision-making using conditional statements, managing edge cases like division by zero,
and implementing functions that can handle different types of inputs (vectors, scalars, and
matrices). By combining main scripts with function files, we also learned the importance of
modularity and reusability in code, which improves readability and simplifies debugging.
Overall, the exercises helped in reinforcing MATLAB's capabilities for mathematical
operations and input handling.

B.3 Questions of Curiosity:


1. What is the significance otherwise in switch case statement?

The switch-case statement in MATLAB (and other programming languages) is used for
multi-way branching based on the value of a variable or expression. It allows you to choose
between multiple possible execution paths more efficiently and clearly than using multiple
if-elseif statements. The switch-case structure is useful when you need to compare a
variable to several discrete values and execute different code for each case. Key benefits
include:

 Clarity: It makes the code more readable and easier to understand when there are
multiple conditions.
 Efficiency: It may be more efficient than a long chain of if-elseif statements,
especially when there are many possible outcomes to check.
 Organization: Keeps the code more organized by grouping cases under a single
switch statement.

2. What is the nesting of if statement?


Nesting an if statement means placing one if statement inside another. This is typically
done when you have multiple conditions that depend on one another. For example, the outer
if checks one condition, and if that condition is true, the inner if checks another condition.

Significance of Nested if Statements:

 Complex Conditions: Allows you to handle more complex decision-making


scenarios where you need to evaluate multiple levels of conditions.
 Flow Control: Helps in cases where decisions depend on the outcomes of earlier
conditions, enabling precise control over how the program behaves.

Example of a nested if statement:


if a > 0

if b > 0

disp('Both a and b are positive');

else

disp('a is positive but b is not');

end

else

disp('a is not positive');

end

You might also like