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

UNIT-4_MATLAB PROGRAMMING_QUESTION BANK_SOLUTION

Uploaded by

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

UNIT-4_MATLAB PROGRAMMING_QUESTION BANK_SOLUTION

Uploaded by

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

Course Code: 20EC0454 R20

SIDDHARTH INSTITUTE OF ENGINEERING & TECHNOLOGY


(AUTONOMOUS)
(Approved by AICTE, New Delhi& Affiliated to JNTUA, Ananthapuramu)
(Accredited by NBA for Civil, EEE, Mech., ECE & CSE)
(Accredited by NAAC with ‘A+’ Grade)
Puttur -517583, Tirupati District, A.P. (India)
QUESTION BANK WITH SOLUTION
Subject with MATLABPROGRAMMING Course & B.Tech. – CSE, CSIT
Code (20EC0454) Branch
Year & Sem IV-B.Tech.&I-Sem Regulation R20
UNIT-IV
INTRODUCTION TO MATLAB

1.A. How program is designed and developed in MATLAB?. [L1] [CO1] [6M]
Design of computer programs to solve complex problems needs to be done in a systematic manner
from the start to avoid time-consuming and frustrating difficulties later in the process. In this section we
show how to structure and manage the program design process.

Algorithms and Control Structures:


• An algorithm is an ordered sequence of precisely need instructions that performs some task in a
amount of time.
• An ordered sequence means that the instructions can be numbered, but an algorithm often must
have the ability to alter the order of its instructions using what is called a control structure.
• There are three categories of algorithmic operations:
• Sequential operations. These instructions are executed in order.
• Conditional operations. These control structures rst ask a question to be answered with a
true/false answer and then select the next instruction based on the answer.
• Iterative operations (loops). These control structures repeat the execution of a block of
instructions
Not every problem can be solved with an algorithm, and some potential algorithmic solutions can fail
because they take too long to find a solution.
Course Code: 20EC0454 R20
Structured Programming
• Structured programming is a technique for designing programs in which a hierarchy of modules is
used, each having a single entry and a single exit point, and in which control is passed downward
through the structure without unconditional branches to higher levels of the structure.
• In MATLAB these modules can be built-in or user-defined functions. Structured programs are
easier to write because the programmer can study the overall problem first and deal with the
details later.
• Modules (functions) written for one application can be used for other applications (this is called reusable
code).
• Structured programs are easier to understand and modify, especially if meaningful names are
chosen for the modules and if the documentation clearly identifies the module’s task.
Top-down Design:
• The top-design approach is used to design and develop the program in MTALAB.
• Top-down design is the process of starting with a large task and breaking it down into smaller,
more easily understandable pieces (subtasks) which perform a portion of the desired task.
• Each Programs are usually written to fill some subtask may in turn be subdivided into smaller
subtasks if necessary.
• Once the program is divided into small pieces, each piece can be coded and tested independently
1. b Compute the perimeter p and the area A of a triangle whose sides are a, b, and c. The formulas
are p=a+b+c, s= (P/2), A=√𝒔(𝒔 − 𝒂)(𝒔 − 𝒃)(𝒔 − 𝒄), with suitable steps.. [L2][CO4][6M]
Steps and Formulas:
1. Calculate the perimeter P:
P=A+B+C
2. Calculate the semi-perimeter S:
S=P/2
3. Calculate the area A using Heron's formula:
A=s⋅(s−a)⋅(s−b)⋅(s−c)
MATLAB Code
function [p, A] = triangle Properties(a, b, c)
% triangle Properties calculates the perimeter and area of a triangle
% given its sides a, b, and c.
%
% Input:
% a, b, c - lengths of the sides of the triangle
%
% Output:
% p - perimeter of the triangle
% A - area of the triangle calculated using Heron's formula
% Step 1: Calculate the perimeter
p = a + b + c;
% Step 2: Calculate the semi-perimeter
s = p / 2;
% Step 3: Calculate the area using Heron's formula
A = sqrt(s * (s - a) * (s - b) * (s - c));
End
Course Code: 20EC0454 R20
Explanation
• Function Definition: The function triangle Properties takes three inputs (a, b, c), representing
the sides of the triangle, and returns two outputs: the perimeter (p) and area (A).
• Step 1 (Perimeter): Sum up the sides A, B and C to get the perimeter.
• Step 2 (Semi-Perimeter): Divide the perimeter by 2 to get the semi-perimeter, S.
• Step 3 (Area): Use Heron’s formula to compute the area by substituting, S,A,B and C into the
formula
Example
To calculate the perimeter and area of a triangle with sides a=5,b=6, and c=7, call the function
as follows:
MATLAB Code:
[p, A] = triangleProperties(5, 6, 7);
disp (['Perimeter: ', num2str(p)]);
disp(['Area: ', num2str(A)]);
2. a. Explain about Conditional Operations with suitable example. [L2] [CO5] [6M]
• Conditional operations allow a program to make decisions based on specified conditions.
• These operations control the flow of the program by executing certain code blocks if a
condition is true and potentially different code blocks if the condition is false
Types of Conditional Statements:
1. if Statement: Executes a block of code if a specified condition is true.
2. if-else Statement: Executes one block of code if a condition is true and another if it’s
false.
3. if-elseif-else Statement: Checks multiple conditions in sequence and executes the
corresponding code block for the first true condition.
4. switch-case Statement: An alternative to if-elseif for checking specific values of a
variable.
5. Logical Operators: Used within conditions, such as && (AND), || (OR), and ~ (NOT)
Syntax and Examples
1 . if Statement
• Executes code only if the condition is true.
% Example: Check if a number is positive
Number = 5;
If ( Number > 0)
disp('The number is positive.');
end
output:
number is 5 (greater than 0), MATLAB will display "The number is positive."
2. if-else Statement
• Chooses between two options based on the condition
% Example: Check if a number is positive or non-positive
number = -3;
if number > 0
disp('The number is positive.');
else
disp('The number is non-positive.');
end
output:
Course Code: 20EC0454 R20
number is -3, MATLAB will display "The number is non-positive."
3. if-elseif-else Statement
• Useful when there are multiple conditions to check.
% Example: Determine if a number is positive, zero, or negative
number = 0
;
if number > 0
disp('The number is positive.');
elseif number == 0
disp('The number is zero.');
else
disp('The number is negative.');
end
OUTPUT:
"The number is zero" because number is equal to 0.
4. switch-case Statement
• Best used when comparing a variable against specific values .matlab
% Example: Determine the day of the week
day = 'Tuesday';
switch day
case 'Monday'
disp('Start of the work week.');
case 'Tuesday'
disp('Second day of the work week.');
case 'Friday'
disp('Last day of the work week.');
otherwise
disp('It is a mid-week day.');
end
UTPUT:
Here, MATLAB will display "Second day of the work week" because day is "Tuesday".
5. Using Logical Operators
• Combine multiple conditions with logical operators.
% Example: Check if a number is within a range
number = 8;
if number >= 5 && number <= 10
disp('The number is within the range of 5 to 10.');
else
disp('The number is out of range.');
end
OUTPUT:
Since number is 8, which is within the range, MATLAB will display "The number is within the range of 5
to 10."
Course Code: 20EC0454 R20
2. b. Explain about Iterative Operations with suitable example.? [L5][CO3] [6M]
• Iterative operations, also known as loops, allow repetitive execution of a code block in MATLAB
• Loops are essential for automating tasks, processing collections of data, or repeating a calculation
until a specified condition is met.
Types of Loops in MATLAB
1. for Loop: Repeats a block of code a specified number of times.
2. while Loop: Repeats a block of code as long as a condition remains true.
1. for Loop
The for loop is used when you know the exact number of times you want to repeat a task.

Syntax
for index = startValue:endValue
% Code to repeat
end
Example
Suppose we want to calculate the sum of the first 5 positive integers:
sumValue = 0; % Initialize sum
for i = 1:5
sumValue = sumValue + i;
end
disp(['The sum of the first 5 positive integers is: ', num2str(sumValue)]);
Here’s how this code works:
• The for loop iterates from i = 1 to i = 5.
• Each iteration adds the current value of i to sumValue.
• After the loop completes, sumValue holds the result (15), which MATLAB displays.
2. while Loop:
The while loop repeats a code block as long as a specified condition is true. It's useful when the
number of iterations isn’t predetermined.
Course Code: 20EC0454 R20

Syntax
while condition
% Code to repeat
end
Example
Suppose we want to calculate how many terms are needed for the sum of positive integers to
exceed 20.
sumValue = 0; % Initialize sum
i = 1; % Start with the first positive integer
while sumValue <= 20
sumValue = sumValue + i;
i = i + 1; % Increment to the next integer
end
disp(['The sum exceeds 20 after adding ', num2str(i - 1), ' terms.']);
Explanation:
• The while loop continues as long as sumValue is less than or equal to 20.
• For each loop iteration, the next integer (i) is added to sumValue.
• The loop stops when sumValue becomes greater than 20. MATLAB then displays the
number of terms needed to exceed this sum.
Nested Loops
Sometimes, loops are nested, with one loop inside another. This is often used in matrix operations
or multi-dimensional data processing.
Example
Suppose we want to create a 3x3 matrix where each element is the product of its row and column
matrix = zeros(3, 3); % Initialize a 3x3 matrix
for i = 1:3
for j = 1:3
matrix(i, j) = i * j;
Course Code: 20EC0454 R20
end
end
disp('3x3 matrix with each element as the product of row and column indices:');
disp(matrix);
Explanation:
• The outer loop iterates over rows (i = 1 to 3), while the inner loop iterates over columns (j
= 1 to 3).
• For each element at position (i, j), the value i * j is assigned.
3. a. List various relational operators available in MATLAB with detailed description.
[L1][CO1][6M]
• Relational operators in MATLAB are used to compare values or arrays and return a logical result
(either true or false).
• These operators are essential for creating conditions in conditional and iterative statements.
• MATLAB has six relational operators to make comparisons between arrays.
• Note that the equal to operator consists of two = = signs, not a single = sign as you might expect.
The single = sign is the assignment, or replacement, operator in MATLAB

List of Relational Operators in MATLAB


1. == (Equal To)
o Description: Checks if two values are equal.
o Example: 5 == 5 returns true.
o Usage: Often used to check if two variables have the same value.
Example:
a = 5;
b = 5;
result = (a == b); % result is true (1)
2. ~= (Not Equal To)
o Description: Checks if two values are not equal.
o Example: 5 ~= 3 returns true.
o Usage: Used when we want to ensure two values are different.
Example:
a = 5;
b = 3;
result = (a ~= b); % result is true (1)
3. < (Less Than)
o Description: Checks if the value on the left is less than the value on the right.
o Example: 3 < 5 returns true.
o Usage: Commonly used to check range constraints.
Example:
a = 3;
b = 5;
result = (a < b); % result is true (1)
Course Code: 20EC0454 R20
4. > (Greater Than)
o Description: Checks if the value on the left is greater than the value on the right.
o Example: 5 > 3 returns true.
o Usage: Useful in conditions where values are expected to exceed a certain limit.
Example:
a = 5;
b = 3;
result = (a > b); % result is true (1)
5. <= (Less Than or Equal To)
o Description: Checks if the value on the left is less than or equal to the value on the right.
o Example: 3 <= 3 returns true.
o Usage: Useful when setting a maximum threshold inclusive of the boundary.
Example:
a = 3;
b = 3;
result = (a <= b); % result is true (1)
6. >= (Greater Than or Equal To)
o Description: Checks if the value on the left is greater than or equal to the value on the
right.
o Example: 5 >= 3 returns true.
o Usage: Often used in situations where a minimum inclusive threshold is required.
Example:
a = 5;
b = 3;
result = (a >= b); % result is true (1)
.
3 .b. How Logical Operators and Functions are handled in MATLAB? [L3][CO2] [6M]
• logical operators and functions are used to evaluate expressions that return true (1) or false
(0).
• Logical operators enable the combination of multiple conditions, and logical functions
facilitate decision-making processes, data filtering, and conditional executions
Logical Operators in MATLAB
1. && (Logical AND)
1. Description: Returns true if both operands are true; otherwise, returns false.
2. Usage: Typically used in conditions where two or more conditions must all be true.
3. Example: A && B returns true only if both A and B are true.
• a = 5;
• b = 10;
• result = (a > 0) && (b < 15); % result is true (1) because both conditions are true
2.|| (Logical OR)
• Description: Returns true if at least one of the operands is true; otherwise, returns false.
• Usage: Useful when only one of multiple conditions needs to be true.
• Example: A || B returns true if either A or B is true.
• a = 5;
• b = 10;
• result = (a < 0) || (b < 15); % result is true (1) because the second condition is true
~ (Logical NOT)
Course Code: 20EC0454 R20
• Description: Reverses the logical state of the operand (i.e., true becomes false, and false
becomes true).
• Usage: Often used to negate a condition.
• Example: ~A returns true if A is false
• a = false;
• result = ~a; % result is true (1) because a is false
Logical Functions in MATLAB
1. all
o Description: Checks if all elements in an array satisfy a condition.
o Usage: Returns true if all elements are true; otherwise, returns false.
o Example: all([1, 1, 0]) returns false because not all elements are 1.
A = [true, true, false];
result = all(A); % result is false (0)
2. any
• Description: Checks if any element in an array satisfies a condition.
• Usage: Returns true if at least one element is true.
• Example: any([0, 0, 1]) returns true because at least one element is 1.
A = [false, false, true];
result = any(A); % result is true (1)
3. xor (Exclusive OR)
• Description: Returns true if one and only one of the operands is true.
• Usage: Used for exclusive conditions where only one condition should be true.
• Example: xor(A, B) returns true if either A or B is true, but not both.
a = true;
b = false;
result = xor(a, b); % result is true (1) because only one of a or b is true
4.find
• Description: Returns the indices of elements in an array that satisfy a condition.
• Usage: Used for locating elements within an array.
• Example: find(A > 0) returns the indices of elements in A that are greater than 0.
A = [0, 3, -1, 5];
indices = find(A > 0); % indices is [2, 4]
5.isempty
• Description: Checks if an array is empty.
• Usage: Returns true if the array has no elements.
• Example: isempty([]) returns true.
A = [];
result = isempty(A); % result is true (1).
Course Code: 20EC0454 R20
4. a. If x = [5,-3,18,4] and y = [-9,13,7,4], what will be theresult of the following operations? Use
MATLAB to check your answer. [L1][CO1][6M]
a) z = ~y > x
b) z = x & y
c) z = x | y
d) z= x or (x,y)
Given Data
• x=[5,−3,18,4]
• y=[−9,13,7,4]
a) z= y>x:
In this operation, MATLAB first computes the bitwise NOT of each element in y, then compares
it to the corresponding element in x.
1. Bitwise NOT (~y): In MATLAB, the ~ operator flips each bit of the integer, producing the
bitwise complement.
o For y = [-9, 13, 7, 4], the bitwise NOT (~y) gives: y=[8,−14,−8,−5]
2. Comparison (~y > x): MATLAB then checks if each element in ~y is greater than the
corresponding element in x, producing a logical array.
o 8>5,−14>−3,−8>18,−5>4 gives: [True, False, False, False]
Result: z = [True, False, False, False]
b) z=x & y
The & operator performs a bitwise AND operation between each pair of corresponding elements
in x and y.
• Bitwise AND: In binary, only bits that are 1 in both numbers remain 1; otherwise, they
become 0.
o For x & y:
o [5&−9,−3&13,18&7,4&4]=[5,13,2,4]
Result: z = [5, 13, 2, 4]
c) z=x∣y
The | operator performs a bitwise OR operation between each pair of elements in x and y.
• Bitwise OR: In binary, if at least one of the bits in either number is 1, the resulting bit is 1.
o For x | y:
o [5∣−9,−3∣13,18∣7,4∣4]=[−9,−3,23,4]
Result: z = [-9, -3, 23, 4]

d) z=xor(x,y)
The xor function computes the bitwise XOR for each corresponding element in x and y.
• Bitwise XOR: In binary, a bit is 1 if it is different in the two numbers (i.e., one is 1 and the
other is 0).
o For xor(x, y):
o [5 XOR −9,−3 XOR 13,18 XOR 7,4 XOR 4]=[−14,−16,21,0]
o Result: z = [-14, -16, 21, 0]
Course Code: 20EC0454 R20
4. b Suppose that x = [-9, -6, 0, 2, 5] and y = [-10, -6 2, 4,6]. What is the result of the
following operations? Determine the answers by hand, and then use MATLAB to
check your answers.
a) z = (x < y)
b) z = (x > y)
c) z = (x ~= y)
d) z = (x == y)
e) z=(x>2)
Given Data
• x=[−9,−6,0,2,5]
• y=[−10,−6,2,4,6]
a) z=(x<y)z = (x < y)z=(x<y)
This operation compares each corresponding element in X and Y to see if x[i]<y[i].
1. −9<−10: False
2. −6<−6: False
3. 0<2: True
4. 2<4: True
5. 5<6: True
Result: z = [False, False, True, True, True]
b) z=(x>y)z = (x > y)z=(x>y)
This operation compares each corresponding element in X and Y to see if x[i]>y[i].
1. −9>−10: True
2. −6>−6: False
3. 0>2: False
4. 2>4: False
5. 5>6: False
Result: z = [True, False, False, False, False]
c) z=(x≠y)z = (x \neq y)z=(x =y)
This operation checks if each element in X is not equal to the corresponding element in Y.
1. −9≠−10: True
2. −6≠−6: False
3. 0≠2: True
4. 2≠4: True
5. 5≠6: True
Result: z = [True, False, True, True, True]
d) z=(x==y)z = (x == y)z=(x==y)
This operation checks if each element in X is equal to the corresponding element in Y.
1. −9==−10: False
2. −6==−6: True
3. 0==2: False
4. 2==4: False
5. 5==6: False
Result: z = [False, True, False, False, False]
e) z=(x>2)z = (x > 2)z=(x>2)
This operation checks if each element in X is greater than 2.
1. −9>2: False
2. −6>2: False
Course Code: 20EC0454 R20
3. 0>2: False
4. 2>2: False
5. 5>2: True
Result: z = [False, False, False, False, True]
Let’s now use MATLAB code to verify these results.
The results from MATLAB confirm our manual calculations:
1. a) z=(x<y): z = [False, False, True, True, True]
2. b) z=(x>y): z = [True, False, False, False, False]
3. c) z=(x≠y) :z = [True, False, True, True, True]
4. d) z=(x==y):z = [False, True, False, False, False]
5. e) z=(x>2): z = [False, False, False, False, True]
5. a. Explain“ if ” Statement in MATLABWith suitable flow chart. [L5][CO1] [6M]
• The if statement is a conditional statement used to execute code based on a logical
condition.
• If the specified condition evaluates to true (1), the code block within the if statement
runs.
• If it evaluates to false (0), the program skips the if block or executes alternative
conditions within elseif or else blocks if they are provided.
Syntax of if Statement in MATLAB
if condition
% Code to execute if condition is true
elseif another_condition
% Code to execute if the first condition is false but this one is true
else
% Code to execute if all conditions are false
End
Explanation
• if condition: The program checks the condition after if.
• elseif: Checks an alternative condition if the first if condition is false.
• else: Executes if none of the if or elseif conditions are true.
• end: Marks the end of the if block.
Example of an if Statement
Consider a situation where you want to check a variable's value and execute different actions based on its
value.
x = 10;
if x > 10
disp('x is greater than 10');
elseif x == 10
disp('x is equal to 10');
else
disp('x is less than 10');
end
Explanation of example:
• If x is 10, MATLAB displays x is equal to 10.
• If x is greater than 10, MATLAB displays x is greater than 10.
• If x is less than 10, MATLAB displays x is less than 10.
Course Code: 20EC0454 R20
Flowchart of the if Statement

5 .b. Write the following statements to use only one if statement using MATLAB
a)if x < y then, w = xy.
b)if a= b then, u= sinh-1(ab). [L3][CO4] [6M]
You want to create a combined if statement that checks:
1. Condition 1: x<y If true, MATLAB should set W to the product of X and Y.
2. Condition 2: a=b. If true, MATLAB should set U to the inverse hyperbolic sine of the
product of ’ a’ and ‘b’ .
The goal is to check both conditions at once in a single if statement. MATLAB will only
execute the code inside the if block if both conditions are true.
Step-by-Step Solution
1. Logical AND in MATLAB: &&
In MATLAB, the && operator is used to combine two logical conditions so that both must be true
for the overall statement to be true. For example, if you write (x < y) && (a == b),
MATLAB will:
• First, check if x < y.
• If x < y is true, MATLAB will check if a == b.
• The code inside the if block will only execute if both conditions are true. If either
condition is false, the code inside the if block is skipped.
2. Calculations for w and u
To implement the required calculations:
• For w: The first condition checks x < y. If this condition is met, we define w as the
product of x and y (i.e., w = x * y).
• For u: The second condition checks if a == b. If this condition is true, we calculate u as
the inverse hyperbolic sine of a * b. In MATLAB, asinh is the function that computes
the inverse hyperbolic sine (sinh inverse) of a value.
CODE:
if (x < y) && (a == b)
w = x * y; % Calculates w if x < y is true
u = asinh(a * b); % Calculates u if a == b is true
end
Example
Consider values for x, y, a, and b:
Course Code: 20EC0454 R20
x = 3;
y = 5;
a = 2;
b = 2;
• Step 1: MATLAB evaluates x < y, which is 3 < 5 and therefore true.
• Step 2: MATLAB evaluates a == b, which is 2 == 2 and also true.
Since both conditions are true, MATLAB performs the following calculations:
• w = x * y results in w = 3 * 5 = 15.
• u = asinh(a * b) results in u = asinh(2 * 2) = asinh(4).
So, the final values are w = 15 and u = asinh(4), where u is approximately 2.0634.
Summary Flowchart
Here's a simple flow of the process in the if statement:
1. Start.
2. Check x < y.
o If false, skip the if block.
o If true, go to the next condition.
3. Check a == b.
o If false, skip the if block.
o If true, execute both w = x * y and u = asinh(a * b).
4. End
6. a. Explain “ else ” and “elseif” Statement in MATLAB With suitable flow chart.
[L3][CO4] [6M]
else and elseif are used in conditional statements to provide additional paths for
code execution based on specific conditions.
1. The elseif Statement
• The elseif statement is used when you have multiple conditions to check sequentially.
• It comes after an if condition and only executes if the initial if condition is false but the elseif
condition is true. You can have multiple elseif conditions following an if.
Syntax:
if condition1
% Code to execute if condition1 is true
elseif condition2
% Code to execute if condition1 is false and condition2 is true
elseif condition3
% Code to execute if both condition1 and condition2 are false, but condition3 is true
...
else
% Code to execute if all previous conditions are false
end
xample:
score = 85;
if score >= 90
grade = 'A';
elseif score >= 80
grade = 'B';
elseif score >= 70
grade = 'C';
else
grade = 'D';
end
Course Code: 20EC0454 R20
Explanation:
• if score is 90 or more, it assigns grade = 'A'.
• If score is between 80 and 89, it assigns grade = 'B'.
• If score is between 70 and 79, it assigns grade = 'C'.
• If none of the conditions are met (score < 70), it assigns grade = 'D'.
flow chart

2. The else Statement


The else statement is the final part of an if block, providing a default action when none of the if or elseif
conditions are true. Only one else statement can exist, and it must come at the end of the if structure.
Syntax:
if condition1
% Code to execute if condition1 is true
elseif condition2
% Code to execute if condition1 is false and condition2 is true
else
% Code to execute if all previous conditions are false
end
Example:
temp = 30;
if temp > 35
weather = 'Hot';
elseif temp > 20
weather = 'Warm';
else
weather = 'Cool';
end
Explanation:
• If temp is above 35, it assigns weather = 'Hot'.
• If temp is between 20 and 35, it assigns weather = 'Warm'.
• If temp is 20 or below, it assigns weather = 'Cool'.
Course Code: 20EC0454 R20
flow chart

6. b. Write a program that accepts a numerical value x from 0 to 100 as input and computes
and displays the corresponding letter grade given by the following table.
a) x ≥90
b) 80≤x ≤89
c) 70 ≤x ≤79
d) 60≤x ≤69
e) x <60
a. Use nested if statements in your program (do not use elseif).
b. Use only elseif clauses in your program. [L1][CO4] [6M]

1. Program using nested if statements (no elseif).


2. Program using only elseif clauses.
1. Program Using Nested if Statements
In this program, we use nested if statements to handle each range of values. Each if block contains
another if to check further conditions.
% Accept input from user
x = input('Enter a numerical value between 0 and 100: ');

% Nested if statement structure


if x >= 0 && x <= 100
if x >= 90
grade = 'A';
else
if x >= 80
grade = 'B';
else
if x >= 70
grade = 'C';
else
if x >= 60
grade = 'D';
else
grade = 'F';
end
end
end
end
Course Code: 20EC0454 R20
fprintf('The grade is: %s\n', grade);
else
fprintf('Invalid input. Please enter a value between 0 and 100.\n');
end
Explanation:
• The outer if checks if x is between 0 and 100.
• Each nested if checks if x falls within a specific grade range.
• The grades are assigned based on the first true condition found, without using elseif.
2. Program Using Only elseif Clauses
In this approach, we streamline the code by using elseif clauses, which allows MATLAB to check each
condition sequentially without needing multiple nested if blocks.
% Accept input from user
x = input('Enter a numerical value between 0 and 100: ');

% Using only elseif clauses


if x >= 90 && x <= 100
grade = 'A';
elseif x >= 80
grade = 'B';
elseif x >= 70
grade = 'C';
elseif x >= 60
grade = 'D';
elseif x < 60 && x >= 0
grade = 'F';
else
fprintf('Invalid input. Please enter a value between 0 and 100.\n');
return; % Exit the program for invalid input
end

fprintf('The grade is: %s\n', grade);


Explanation:
• Each elseif checks a specific range, simplifying the program by eliminating nesting.
• elseif clauses are used to check each condition only if the previous ones are false, creating a
more readable and efficient structure.
• The final else provides a message for invalid input if x is not between 0 and 100.
7a. Explain “for loop” Statement in MATLAB With suitable example.. [[L5][CO3] [6M]
a for loop is used to repeat a set of commands a specified number of times. It iterates over a
sequence of values and executes a block of code for each value in that sequence.
Syntax of for Loop in MATLAB:
for index = start_value : increment : end_value
% Code to execute in each iteration
End
Explanation:
• index: The loop variable that takes on each value in the specified range.
• start_value: The initial value for the loop variable.
• increment: The amount by which the loop variable increases (or decreases) in each iteration. If omitted,
MATLAB uses an increment of 1.
• end_value: The final value for the loop variable.
Example: Calculating the Sum of Numbers from 1 to 10
Let's say we want to calculate the sum of all numbers from 1 to 10.
sum_value = 0; % Initialize the sum
Course Code: 20EC0454 R20
for i = 1:10
sum_value = sum_value + i; % Add the current value of i to sum_value
end

fprintf('The sum of numbers from 1 to 10 is: %d\n', sum_value);


Explanation:
• The for loop iterates from i = 1 to i = 10.
• In each iteration, the current value of i is added to sum_value.
• After completing all iterations, sum_value contains the total sum of numbers from 1 to 10, which
is 55.
Example with Increment
If we want to display only the even numbers between 1 and 10:
for n = 2:2:10
fprintf('%d\n', n);
end
Explanation:
• Here, n starts at 2 and increments by 2 in each iteration, so it only takes even values: 2, 4, 6, 8, and
10.
• The loop displays each even number in the range by printing n in each iteration.
Flowchart of a for Loop

7 b.Write a script file to compute the sum of the first 15 terms in the series 5 k2-2k,
k=1, 2, 3, . . . , 15. [L2][CO1] [6M]
To compute the sum of the first 15 terms in the series 5k2−2k5k^2 - 2k5k2−2k where k=1,2,3,…,15k
= 1, 2, 3, \ldots, 15k=1,2,3,…,15, we can use a for loop to iterate through each term and add it to a
running total. Here’s how to create a script file in MATLAB to perform this calculation
MATLAB Script
% Initialize the sum to zero
sum_series = 0;
% Loop through each value of k from 1 to 15
for k = 1:15
% Calculate the current term of the series
term = 5 * k^2 - 2 * k;
% Add the current term to the running total
sum_series = sum_series + term;
Course Code: 20EC0454 R20
end
% Display the result
fprintf('The sum of the first 15 terms in the series is: %d\n', sum_series);
Explanation
1. Initialize sum_series to 0 to store the cumulative sum of the terms.
2. Use a for loop to iterate from k = 1 to k = 15.
3. Calculate each term using the formula 5k2−2k5k^2 - 2k5k2−2k and add it to sum_series.
4. Display the final sum using fprintf.
Problem Analysis
The given series formula is:
Term k=5k^2−2k
where k represents each term in the sequence from 1 to 15.
Detailed Calculation for Each Iteration
Let’s calculate each term manually for k=1k = 1k=1 through k=15k = 15k=15 to see how the script adds
up these terms.
1. For k=1:
o Compute the term: 5×(1^2)−2×1=5−2=3.
o Add to sum_series: 0+3=30 + 3 = 30+3=3.
o Cumulative sum after this iteration: 3.
2. For k=2k = 2k=2:
o Compute the term: 5×(2^2)−2×2=20−4=16
o Add to sum_series: 3+16=19.
o Cumulative sum after this iteration: 19.
3. For k=3k = 3k=3:
o Compute the term: 5×(3^2)−2×3=45−6=39.
o Add to sum_series: 19+39=58.
o Cumulative sum after this iteration: 58.
4. For k=4k = 4k=4:
o Compute the term: 5×(4^2)−2×4=80−8=72.
o Add to sum_series: 58+72=130
o Cumulative sum after this iteration: 130.
5. For k=5k = 5k=5:
o Compute the term: 5×(5^2)−2×5=125−10=115
o Add to sum_series: 130+115=245.
o Cumulative sum after this iteration: 245.
6. For k=6k = 6k=6:
o Compute the term: 5×(6^2)−2×6=180−12=168.
o Add to sum_series: 245+168=413.
o Cumulative sum after this iteration: 413.
7. For k=7k = 7k=7:
o Compute the term: 5×(7^2)−2×7=245−14=231.
o Add to sum_series: 413+231=644.
o Cumulative sum after this iteration: 644.
8. For k=8k = 8k=8:
o Compute the term: 5×(8^2)−2×8=320−16=304.
o Add to sum_series: 644+304=948.
o Cumulative sum after this iteration: 948.
9. For k=9k = 9k=9:
o Compute the term: 5×(9^2)−2×9=405−18=387.
o Add to sum_series: 948+387=1335.
o Cumulative sum after this iteration: 1335.
Course Code: 20EC0454 R20
10. For k=10k = 10k=10:
o Compute the term: 5×(10^2)−2×10=500−20=480.
o Add to sum_series: 1335+480=1815.
o Cumulative sum after this iteration: 1815.
11. For k=11k = 11k=11:
o Compute the term: 5×(11^2)−2×11=605−22=583.
o Add to sum_series: 1815+583=2398.
o Cumulative sum after this iteration: 2398.
12. For k=12k = 12k=12:
o Compute the term: 5×(12^2)−2×12=720−24=696.
o Add to sum_series: 2398+696=3094
o Cumulative sum after this iteration: 3094.
13. For k=13k = 13k=13:
o Compute the term: 5×(13^2)−2×13=845−26=819.
o Add to sum_series: 3094+819=3913.
o Cumulative sum after this iteration: 3913.
14. For k=14k = 14k=14:
o Compute the term: 5×(14^2)−2×14=980−28=952.
o Add to sum_series: 3913+952=4865.
o Cumulative sum after this iteration: 4865.
15. For k=15k = 15k=15:
o Compute the term: 5×(15^2)−2×15=1125−30=1095.
o Add to sum_series: 4865+1095=5960.
o Cumulative sum after this iteration: 5960.
Final Output
The final cumulative sum after all iterations is:
Sum of first 15 terms=5960
8. a. Write a program using the switch structure to input one angle, whosevalue may be 45, -45,
135, or -1350, and display the quadrant (1, 2, 3, or 4) containing the angle.? [L3][CO2] [6M]
• The switch structure to determine and display the quadrant based on an input angle value.
• This program assumes the angle values are restricted to 454545, −45-45−45, 135135135, or
−135-135−135, which fall into different quadrants in standard position.
MATLAB Code:
% Input an angle from the user
angle = input('Enter an angle (45, -45, 135, or -135): ');
% Use switch structure to determine the quadrant
switch angle
case 45
quadrant = 1; % 45 degrees is in Quadrant 1
case -45
quadrant = 4; % -45 degrees is in Quadrant 4
case 135
quadrant = 2; % 135 degrees is in Quadrant 2
case -135
quadrant = 3; % -135 degrees is in Quadrant 3
otherwise
disp('Invalid angle. Please enter one of the following: 45, -45, 135, or -135.');
return; % Exit the program if an invalid angle is entered
end
Course Code: 20EC0454 R20
% Display the result
fprintf('The angle %d degrees is in Quadrant %d.\n', angle, quadrant);
Explanation
1. Input: The user is prompted to enter an angle. This should be one of the values: 45, −45 135 OR -135.
2. Switch Structure: The switch statement evaluates the variable angle:
o case 45: If the angle is 45∘.it corresponds to Quadrant 1.
o case -45: If the angle is −45∘.it corresponds to Quadrant 4.
o case 135: If the angle is 135∘. it corresponds to Quadrant 2.
o case -135: If the angle is −135∘, it corresponds to Quadrant 3.
3. Invalid Input Handling: If the user enters any value other than 45,-45 135 or −135, the otherwise block
runs, displaying an error message and ending the program.
4. Display Output: For valid inputs, the program displays the quadrant containing the specified angle.
Example Outputs
1. Input: 45
o Output: The angle 45 degrees is in Quadrant 1.
2. Input: -45
o Output: The angle -45 degrees is in Quadrant 4.
3. Input: 135
o Output: The angle 135 degrees is in Quadrant 2.
4. Input: -135
o Output: The angle -135 degrees is in Quadrant 3.
5. Invalid Input: 90
o Output: Invalid angle. Please enter one of the following: 45, -45, 135, or
-135.
8. b. Explain “ xy Plotting Functions” in MATLAB.? [L2][CO1] [6M]
• In MATLAB, "xy plotting functions" are used to create two-dimensional plots, allowing you
to visualize data with one variable on the x-axis and another on the y-axis.
• These functions are particularly useful for analyzing the relationship between two variables
and creating a wide range of 2D graphs.
• The most commonly used plotting function in MATLAB is plot, but MATLAB also offers
other functions to enhance data visualization.
Key xy Plotting Functions in MATLAB
1. plot
• Description: Creates a basic xy plot, where the x-data and y-data are connected by lines.
• Syntax: plot(x, y, 'LineSpec')
o x and y are vectors of the same length representing the coordinates of the points.
o 'LineSpec' is an optional argument for customizing line color, style, and marker type.
• Example:
x = 0:0.1:10;
y = sin(x);
plot(x, y, '-r'); % Plots a red line for the sine function
title('Sine Wave');
xlabel('x');
ylabel('sin(x)');
2. plot3
• Description: Creates a 3D plot where points are connected by lines in three dimensions.
• Syntax: plot3(x, y, z, 'LineSpec')
o x, y, and z are vectors representing 3D coordinates.
• Example:
t = 0:0.1:10;
x = sin(t);
y = cos(t);
Course Code: 20EC0454 R20
z = t;
plot3(x, y, z, '-b'); % Plots a blue line in 3D space
title('3D Helix');
xlabel('x');
ylabel('y');
zlabel('z');
3. loglog, semilogx, and semilogy
• Description: Plot data on logarithmic scales.
o loglog: Both x-axis and y-axis are logarithmic.
o semilogx: Only the x-axis is logarithmic.
o semilogy: Only the y-axis is logarithmic.
• Example:
x = logspace(0, 2, 100); % Logarithmic spaced vector
y = x.^2;
loglog(x, y); % Log-log plot of x^2
title('Log-Log Plot of x^2');
xlabel('x');
ylabel('y = x^2');
4. scatter
• Description: Creates a scatter plot, where each point's position is determined by x and y, and you can
control the marker size and color.
• Syntax: scatter(x, y, size, color)
o size specifies the size of each marker.
o color specifies the color of each marker.
• Example:
x = rand(1, 100); % Random x-coordinates
y = rand(1, 100); % Random y-coordinates
scatter(x, y, 50, 'filled'); % Scatter plot with filled circles
title('Scatter Plot');
xlabel('x');
ylabel('y');
5. bar and barh
• Description: Creates bar plots, useful for comparing quantities across different categories.
o bar: Vertical bar plot.
o barh: Horizontal bar plot.
• Syntax: bar(x, y) or barh(x, y)
• Example:
categories = {'A', 'B', 'C', 'D'};
values = [10, 20, 15, 25];
bar(values);
set(gca, 'xticklabel', categories);
title('Bar Plot');
xlabel('Categories');
ylabel('Values');
6. area
• Description: Plots data as filled areas, useful for cumulative data or stacked plots.
• Syntax: area(x, y)
• Example:
x = 1:10;
y = [2, 3, 5, 7, 6, 4, 5, 6, 8, 7];
area(x, y); % Area plot
title('Area Plot');
xlabel('x');
ylabel('y');
Course Code: 20EC0454 R20
7. fill
• Description: Plots filled polygons by connecting points. This is used for highlighting regions or custom
shapes.
• Syntax: fill(x, y, color)
• Example:
x = [1, 2, 3, 2];
y = [1, 2, 1, 0];
fill(x, y, 'g'); % Creates a green-filled polygon
title('Filled Polygon');
xlabel('x');
ylabel('y');
9.a. What are the tools available in Interactive Plotting in MATLAB? Give suitable Example..
[L1][CO2] [6M]
Interactive plotting in MATLAB offers tools that make it easy to explore, annotate, and adjust
plots interactively, especially useful for analysis without needing to code every adjustment.
MATLAB’s interactive tools include a set of figure toolbar options for zooming, panning, rotating, data
brushing, and more.
Key Tools for Interactive Plotting in MATLAB
1. Zoom Tool (Zoom In and Zoom Out)
o Description: Allows zooming into specific regions on the plot for detailed analysis.
o Usage: Click the magnifying glass icon in the figure toolbar, then select the region to
zoom in or out.
o Example:
x = linspace(0, 10, 100);
y = sin(x);
plot(x, y);
title('Sine Wave');
xlabel('x');
ylabel('sin(x)');
% Now click on the zoom tool in the figure toolbar to zoom in or out interactively.
2. Pan Tool
o Description: Allows panning (moving) the plot horizontally and vertically for focusing on
specific data regions.
o Usage: Click the hand icon in the figure toolbar, then click and drag to pan the plot.
o Example: Use the code above, but after plotting, select the pan tool to move across the
plot and explore specific areas.
o
3. Rotate 3D Tool
o Description: For 3D plots, allows rotating the view around different axes to get a better
perspective.
o Usage: Click the rotate icon, then click and drag to rotate the plot.
o Example:
[X, Y, Z] = peaks(30);
mesh(X, Y, Z);
title('3D Mesh Plot');
xlabel('X');
ylabel('Y');
zlabel('Z');
% After the plot appears, use the rotate tool in the figure toolbar to adjust the view.
Course Code: 20EC0454 R20
4. Data Cursor (Data Tips)
o Description: Displays the x, y, and z coordinates of specific points when you click on
them.
o Usage: Click on the data cursor icon and click on a point in the plot. A small box will
show the coordinates.
o Example:
x = linspace(0, 10, 100);
y = sin(x);
plot(x, y, '-o');
title('Sine Wave with Data Cursor');
xlabel('x');
ylabel('sin(x)');
% Use the data cursor tool to click on any point and view its coordinates.
5. Data Brushing
o Description: Highlights and selects specific data points, enabling further analysis or
editing.
o Usage: Activate data brushing from the toolbar, then click and drag over points to
highlight them.
o Example:
x = linspace(0, 10, 100);
y = sin(x) + 0.1*randn(1, 100); % Adding some noise
plot(x, y, '-o');
title('Noisy Sine Wave with Data Brushing');
xlabel('x');
ylabel('sin(x) with Noise');
% Use data brushing to highlight noisy points interactively.
6. Annotations
o Description: Adds text, arrows, shapes, and lines to emphasize or annotate points and
regions in the plot.
o Usage: In the figure toolbar, go to Insert > Text Arrow, Rectangle, Ellipse, etc., to add
annotations.
o Example:
x = linspace(0, 10, 100);
y = sin(x);
plot(x, y);
title('Annotated Sine Wave');
xlabel('x');
ylabel('sin(x)');
% To annotate, use the toolbar to insert text or arrows at specific points.
% For instance, mark the peaks with a text arrow.
7. Legend Editing and Axis Labels
o Description: Enables interactive modification of legends, axis labels, and plot titles.
o Usage: Click directly on the legend, title, or axis labels in the plot to edit them on the
figure.
o Example:
x = linspace(0, 10, 100);
y1 = sin(x);
y2 = cos(x);
plot(x, y1, '-r', x, y2, '-b');
Course Code: 20EC0454 R20
legend('Sine', 'Cosine');
title('Interactive Legend Editing Example');
xlabel('x');
ylabel('Function Value');
% Click on the legend, title, or labels in the plot window to edit them interactively.
9. b. Explain plot commands [L2[CO4] ] [6M]
a) plot (x,y),
b) title( )
c) xlabel( )
d) ylabel( )
in MATLAB with an example.
In MATLAB, the plot, title, xlabel, and ylabel commands are essential for creating and
customizing plots. Here’s a detailed explanation of each command with an example.
1. plot(x, y)
• Description: The plot command creates a 2D line plot by plotting the values of y against x. Each value in
x corresponds to a value in y, forming points that are connected by lines.
• Syntax: plot(x, y, 'LineSpec')
o x and y are vectors or arrays of the same length.
o 'LineSpec' is an optional argument that specifies line style, color, and marker.
• Example:
x = 0:0.1:2*pi; % x values from 0 to 2π
y = sin(x); % y is the sine of x
plot(x, y, '-b'); % Plot y vs. x with a blue line
2. title('text')
• Description: The title command adds a title to the top of the plot. This helps identify or describe the
data being visualized.
• Syntax: title('Your Title')
o 'Your Title' is a string that appears at the top of the plot.
• Example:
title('Sine Wave'); % Adds the title "Sine Wave" to the plot
3. xlabel('text')
• Description: The xlabel command labels the x-axis, providing information about what the x-axis values
represent.
• Syntax: xlabel('Your Label')
o 'Your Label' is a string that appears next to the x-axis.
• Example:
• xlabel('x (radians)'); % Labels the x-axis as "x (radians)"
4. ylabel('text')
• Description: The ylabel command labels the y-axis, providing information about what the y-axis values
represent.
• Syntax: ylabel('Your Label')
o 'Your Label' is a string that appears next to the y-axis.
• Example:
ylabel('Amplitude'); % Labels the y-axis as "Amplitude"
10A. Plot the equation y= 0.4 √𝟏. 𝟖 𝒙 for 0 ≤x ≤ 35 and 0 ≤y ≤ 3.5. [L1][CO5]
To plot the equation y=0.4sqrt{1.8x} for the range 0≤x≤35and 0≤y≤3.5 in MATLAB, you can follow
these steps:
1. Define the range for x: Create a vector of x values from 0 to 35.
2. Calculate the corresponding y values using the given equation.
Plot the values and set appropriate limits for both axes.
Course Code: 20EC0454 R20

To simplify the equation:


y=0.41 \sqrt{1.8 x}
we can break it down step-by-step to make it easier to interpret.
Step 1: Simplify the Inside of the Square Root
The term inside the square root is 1.8 xWe can rewrite 1.8 as a fraction:
1.8=9/5
So,
1.8 x=9/5x
Thus, our equation becomes:
y=0.495\sqrt{ 9/5 .x}
Step 2: Move Constants Outside the Square Root
We can factor the constant 9/5 outside the square root:
y=0.4⋅ \sqrt{ {9}/{5}}.sqrt{x }
Step 3: Simplify the Coefficients

So, the simplified form is approximately:

Final Simplified Equation


The simplified equation is:

MATLAB Code
% Define the range for x
x = linspace(0, 35, 100); % 100 points between 0 and 35

% Calculate corresponding y values using the equation


y = 0.4 * sqrt(1.8 * x);

% Create the plot


figure; % Create a new figure window
plot(x, y, 'b', 'LineWidth', 2); % Plot y vs. x with a blue line
title('Plot of y = 0.4 * sqrt(1.8 * x)'); % Add title
xlabel('x'); % Label x-axis
ylabel('y'); % Label y-axis
xlim([0 35]); % Set x-axis limits
ylim([0 3.5]); % Set y-axis limits
Course Code: 20EC0454 R20
grid on; % Add grid for better visibility
Explanation of the Code
1. x = linspace(0, 35, 100);: This line creates a vector x with 100 evenly spaced points between 0
and 35.
2. y = 0.4 * sqrt(1.8 * x);: This computes the values of y for each corresponding value of x using
the given equation.
3. figure;: Opens a new figure window for the plot.
4. plot(x, y, 'b', 'LineWidth', 2);: Plots y against x with a blue line and a line width of 2.
5. title(...), xlabel(...), ylabel(...): These functions set the title and the labels for the x and y
axes.
6. xlim([0 35]); and ylim([0 3.5]);: These functions set the limits for the x and y axes, respectively.
7. grid on;: Adds a grid to the plot for better visualization.
Output
When you run this code in MATLAB, you will see a plot of the equation y=0.41 \sqrt{1.8x} that
spans the specified ranges for both X and Y. The graph will show how y varies as X increases from 0
to 35, highlighting the relationship defined by the equation
10 b. How to plot Three-Dimensional functions in MATLAB with suitable example. [L2][CO2]
[6M]
functions for creating three-dimensional plots. Here we will summarize the basic functions to create
three types of plots:
1. Line plots,
2. SurfaceMesh plots,
3. Contour plots.
Three-Dimensional Line Plots :
Lines in three-dimensional space can be plotted with the plot3 function. For example, the following equations
generate a three-dimensional curve as the parameter t is varied over some range:
x = e-0.05t sin t
y = e-0.05t cos t
z=t
If we let t vary from t= 0 to t= 10 pi, the sine and cosine functions will vary through ve cycles, while the absolute
values of x and y become smaller as t increases. This process results in the spiral curve shown in Figure 5.4–1,
which was produced with the following session.
Its syntax is plot3(x,y,z).
>>t = 0:pi/50:10*pi;
>>plot3(exp(-0.05*t).*sin(t),exp(-0.05*t).*cos(t),t),... xlabel(‘x’),ylabel(‘y’),zlabel(‘z’),grid
Course Code: 20EC0454 R20
SurfaceMesh Plots:
• The function z = f(x, y) represents a surface when plotted on xyz axes, and the mesh function provides
the means to generate a surface plot. Before you can use this function, you must generate a grid of
points in the xy plane and then evaluate the function f (x, y) at these points.
• Purpose: The surf function creates a 3D surface plot where each segment (face) of the grid is
colored according to its height (or Z value). This makes it easy to see gradual changes in value across
the surface.
• Appearance: The plot appears as a solid, continuous surface with a color gradient representing
variations in Z values. Higher values in Z often correspond to warmer colors (e.g., red or yellow),
while lower values might be shown in cooler colors (e.g., blue or green).
• Use Case: Best for continuous data that benefits from visualizing variations in height, peaks, and
troughs. It’s commonly used in topographical data, heat maps, and any context where surface
curvature is important.

Contour Plots
• Topographic plots show the contours of the land by means of constant elevation lines.
• These lines are also called contour lines, and such a plot is called a contour plot.
• If you walk along a contour line, you remain at the same elevation. Contour plots can help you
visualize the shape of a function. They can be created with the contour function, whose syntax is
contour(X,Y,Z).
• You use this function the same way you use the mesh function; that is, rst use the meshgrid function
to generate the grid and then generate the function values

This example demonstrates how to use mesh and surf to plot the function z= sin(\sqrt{x^2 + y^2})
1. Define a grid of x and Y values.
2. Calculate z values based on X and y.
3. Plot the surface using mesh and surf.
MATLAB Code
% Define the range for x and y
x = linspace(-5, 5, 50); % x values from -5 to 5
y = linspace(-5, 5, 50); % y values from -5 to 5
Course Code: 20EC0454 R20

% Create a meshgrid of x and y values


[X, Y] = meshgrid(x, y);

% Define the function z = sin(sqrt(x^2 + y^2))


Z = sin(sqrt(X.^2 + Y.^2));

% Plot the surface using mesh


figure;
mesh(X, Y, Z); % Creates a wireframe 3D plot
title('3D Mesh Plot of z = sin(sqrt(x^2 + y^2))');
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
grid on;

% Plot the surface using surf


figure;
surf(X, Y, Z); % Creates a solid surface 3D plot
title('3D Surface Plot of z = sin(sqrt(x^2 + y^2))');
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
grid on;
colorbar; % Adds a color bar to show the values of Z
Explanation of the Code
1. Creating a Range for X and Y:
o x = linspace(-5, 5, 50); and y = linspace(-5, 5, 50); create vectors for xxx and
yyy from -5 to 5 with 50 points in each, providing a grid of points.
2. Generating the Grid with meshgrid:
o [X, Y] = meshgrid(x, y); creates a grid of coordinates where every combination of xxx and
yyy values will be evaluated. This grid is stored in matrices X and Y.
3. Defining the Function z= sin(\sqrt{x^2 + y^2})
o Z = sin(sqrt(X.^2 + Y.^2)); calculates the z values for each (x,y) pair. The .^ operator
ensures element-wise operations on the grid matrices.
4. Plotting with mesh:
o mesh(X, Y, Z); generates a wireframe plot, showing the structure of the surface without solid
faces.
5. Plotting with surf:
o surf(X, Y, Z); creates a colored surface plot, where color represents the height (value of z).
6. Adding Titles and Labels:
o title, xlabel, ylabel, and zlabel are used to add titles and labels to the axes for better
clarity.
7. Adding a Colorbar:
o colorbar; displays a color bar next to the surf plot, which maps color to the Z values, aiding
interpretation of the surface’s height at different points.
Output
• mesh Plot: Displays a wireframe representation of the 3D function.
• surf Plot: Shows a solid surface plot with color gradients representing the values of zzz across the
surface.
Both plots allow you to understand the behavior of z= sin(\sqrt{x^2 + y^2}) in three
dimensions, visualizing the peaks and valleys based on x and y inputs

You might also like