UNIT-4_MATLAB PROGRAMMING_QUESTION BANK_SOLUTION
UNIT-4_MATLAB PROGRAMMING_QUESTION BANK_SOLUTION
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.
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
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
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]
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
MATLAB Code
% Define the range for x
x = linspace(0, 35, 100); % 100 points between 0 and 35
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