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

TP04 Matlab

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

TP04 Matlab

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

MATLAB Exercises Based on TP 3: Script Files and MATLAB Control

Structures

Exercise 1: Using Loops for Calculation


PN 1
1. Using a for loop, write a program that prompts the user for a number N and calculates the sum S = i=1 2i . 2.
Rewrite the program using a while loop to achieve the same calculation. 3. Verify that both versions give the same
result for any N .

Exercise 2: Using Loops for Product Calculation


QN 1
1. Using a for loop, write a program that prompts the user for a number N and calculates the product P = i=1 i+1 .
2. Rewrite the program using a while loop to achieve the same calculation. 3. Verify that both versions give the same
result for any N .

Exercise 3: Calculating Factorials


1. Using a for loop, write a MATLAB program that reads a number N and calculates its factorial N !. 2. Rewrite the
program using a while loop. 3. Test your code with various values of N and display the results.

Exercise 4: Conditional Statements


1. Write a MATLAB program that reads a value for x. 2. If x < 0, set y = 1; if x > 0, set y = −1; and if x = 0, set
y = 0. 3. Display the value of y based on the input x.

Exercise 5: Using the switch Statement


1. Write a MATLAB program that prompts the user to enter a number. 2. Use a switch statement to display a message
based on the input:
• If the number is 0, display ”Zero”.
• If the number is 1, display ”One”.
• If the number is 2, display ”Two”.
• For any other number, display ”Number is not 0, 1, or 2”.

Exercise 6: Combination of Loops and Conditionals


1. Write a MATLAB program that prompts the user to input a vector of numbers. 2. Using a for loop, count and
display the number of elements that are greater than 10 in the vector. 3. Modify the code to use a while loop to achieve
the same result.

Exercise 7: Nested Control Structures


1. Create a script that generates a 5 × 5 matrix where each element (i, j) is calculated as i × j. 2. Use nested for loops
for the calculations. 3. Display the matrix and highlight the diagonal elements by setting them to zero.

1
TP 4: Advanced MATLAB Exercises with Nested Loops, Functions, and Plotting

1 Introduction
This lab aims to introduce students to the concept of nested loops in MATLAB using both the for and while loops.
Students will learn how to use nested control structures to perform complex calculations and understand the logic behind
iterative loops within loops.

2 Nested Loops Using for and while


2.1 Example of Nested for Loops

This example demonstrates the use of nested for loops to I J S


perform a cumulative sum calculation. 0
s = 0; 1 1
for i = 1 : 3 1 2 2
for j = 1 :3 3 3
s = s + 1; 1 4
end 2 2 5
end 3 6
disp ( [ ’ F i n a l Sum : ’ , num2str ( s ) ] ) ; 1 7
3 2 8
3 9
The inner loop increments the variable s for each combination of i and j, resulting in a total sum.

2.2 Example 2: Note the Difference


This example demonstrates a slight variation in the
placement of the statement s = s + 1; in nested
loops, which changes the behavior of the program. I J S
0
s = 0; 1
for i = 1 : 3 1 2 1
for j = 1 :3 3
% Inner loop does nothing here 1
end 2 2 2
s = s + 1; 3
end 1
disp ( [ ’ F i n a l Sum : ’ , num2str ( s ) ] ) ; 3 2 3
In this example, s is incremented only after the inner 3
for loop completes each iteration, resulting in s being
incremented three times, once per outer loop iteration. Table 1: Values of s during the loop iterations.

2.3 Example 3: Increment and Decrement in Nested Loops


This example demonstrates the effect of incrementing and
decrementing a variable using two separate loops. The vari-
able s is first decremented in the outer loop and then incre-
mented in the inner loop. I J S
0
% I n i t i a l i z e the variable 1
s = 0; 1 2 -1
3
% F i r s t l o o p : Decrement s 1
for i = 1 : 3 2 2 -2
s = s − 1; 3
end 1
3 2 -3
% Second l o o p : Increment s 3
for j = 1 : 5 1
s = s + 1; 2
end 3 2
4
% Display the f i n a l r e s u l t 5
disp ( [ ’ F i n a l v a l u e o f s : ’ , num2str ( s ) ] ) ;

2
2.4 Example 4 : Nested while Loops
Nested while loops can also be used to perform similar iterative calculations. The following example shows how to
accumulate a sum using nested while loops.
i = 1; s = 0;
while i <= 3
j = 1;
while j <= 3
s = s + 1;
j = j + 1;
end
i = i + 1;
end
disp ( [ ’ F i n a l Sum : ’ , num2str ( s ) ] ) ;

This example achieves the same cumulative total by incrementing s in nested while loops.

3 Matrix Operations Using Nested Loops: A Simple Example


Nested loops are a way to process every element of a matrix by iterating over its rows and columns systematically. In
MATLAB, two indices, i and j, are commonly used:
• i: Represents the row index of the matrix.
• j: Represents the column index of the matrix.

3.1 How it Works


A nested loop has two parts:
1. Outer Loop: Controls the row index i. It runs through all the rows of the matrix.
2. Inner Loop: Controls the column index j. For each value of i, the inner loop iterates through all the columns of
that specific row.
This structure ensures every element of the matrix is accessed individually using its indices (i, j).

3.2 Example
Suppose we want to fill a 3 × 3 matrix A such that:
A(i, j) = i + j

Using nested loops, this can be achieved as follows:


% I n i t i a l i z e a 3 x3 m a t r i x w i t h z e r o s
A = zeros ( 3 , 3 ) ;

% F i l l the matrix using nested loops


for i = 1 : 3 % Outer l o o p : I t e r a t e o v e r rows
for j = 1 :3 % I n n e r l o o p : I t e r a t e o v e r columns
A( i , j ) = i + j ; % A s s i g n v a l u e b a s e d on row ( i ) and column ( j )
end
end

% Display the r e s u l t i n g matrix


disp ( ’ Matrix A: ’ ) ;
disp (A ) ;

Explanation of i and j
• When i = 1 (first row), j will take values 1, 2, and 3 (all columns in the first row). The elements A(1, 1), A(1, 2),
and A(1, 3) are filled as 1 + 1, 1 + 2, and 1 + 3, respectively.
• The process repeats for i = 2 (second row) and i = 3 (third row).

3.3 Result
The resulting matrix A will be:
2 3 4
" #
A= 3 4 5
4 5 6

This example demonstrates how i and j control the rows and columns, respectively, in a nested loop structure.

3
4 Exercise
4.1 Exercise: Nested while Loops
1. Write a MATLAB program that uses nested while loops to fill a 4 × 4 matrix N with consecutive numbers starting
from 1. 2. Display the matrix N once it has been fully populated.

4.2 Exercise: Nested for Loops


1. Write a MATLAB script that uses nested for loops to create a 3 × 3 matrix M, where each element M(i, j) is equal
to the product of its indices i × j. 2. Display the matrix M after completing the loop.

5 Functions
A function file allows the creation of custom functions that are not already available in MATLAB. To define a new
function in MATLAB, the function definition must be written in a file with a ‘.m‘ extension (M-File). The name of the
file must match the name of the defined function.
The first line of the function file must follow the syntax below:
Syntax:
function [output arguments] = function-name(input arguments)
The output arguments represent the calculated values returned by the function, and the input arguments are the param-
eters passed to the function (which are not modified).
Note: Unlike scripts, the variables in a function are local variables, meaning they cannot be accessed outside the function.
To execute a function, the working directory must contain the function file. To run the function, type its name followed
by the input arguments in parentheses.

5.1 Example 1: Calculating Factorial


Write a function to calculate the factorial of an integer:
fact.m
function [f] = fact(x)
f = 1;
for i = 1:x
f = f * i;
end
To execute this function, type:
>> fact(5)
ans = 120
This function can also be used to calculate the combination Cnk , which is defined as:

n!
Cnk =
k!(n − k)!

5!
For example, to calculate C53 = 3!(5−3)! :

>> N = 5; k = 3;
>> C = fact(N) / (fact(k) * fact(N - k));
C = 10

5.2 Example 2: Calculating the Hypotenuse


Write a MATLAB program to calculate the hypotenuse of a right triangle given the lengths of the other two sides a and
b: p
c = a2 + b2

4
6 2D Graphism in MATLAB
In addition to numerical computation, MATLAB is well-known for its graphical interface. Vectors and matrices can be
visualized as curves, surfaces, contour plots, etc.
It is possible to label and modify the graphs either from the command line or directly within the graphical window.
The basic function for 2D plotting is plot.

6.1 Basic Syntax


The syntax is:
plot(x, y)
This function plots the curve defined by the set of points (xi , yi ), i = 1, . . . , n. Both vectors x and y must have the same
size.
x: Vector containing the values for the x-axis (abscissa).
y: Vector containing the values for the y-axis (ordinate).

6.2 Examples

Example 1: The sine function


x = 0:0.01:2*pi;
y = sin(x);
plot(x, y); % or simply plot(x, sin(x))
Example 2: The x2 function
x = 0:0.01:10;
y = x.^2; % Element-wise power
plot(x, y); % or simply plot(x, x.^2)

Figure 1: Plot of y = sin(x).

6.3 Plotting Multiple Curves on the Same Figure

You can plot multiple functions on the same figure:


x = 0:0.01:10;
y = x.^2;
y1 = sin(x);
plot(x, y, x, y1);
To distinguish the curves, the plot function includes a
third parameter to specify the color, marker, and line
style for each curve. For example:
plot(x, sin(x), ’c*-’, x, x.^2, ’r+--’);
This command will plot:
• The sine function in cyan with star markers and
a solid line.
• The x2 function in red with plus markers and a
dashed-dotted line.

Figure 2: Plot of y = x2 and y = sin(x).

5
Labels and Titles
The xlabel and ylabel commands are used to label
the axes, and the title command adds a title to the
figure.
Example:
x = 1:10;
plot(x, 2*x);
xlabel(’x-axis’);
ylabel(’y-axis’);
title(’Linear Graph: 2*x’);

Legends
When there are multiple curves in a figure, a legend is
used to distinguish them. The syntax is:

legend(’Curve 1’, ’Curve 2’, ...)

Example:
x = 1:10;
plot(x, 2*x, x, 3*x);
Figure 3: Table of line styles, markers, and colors.
legend(’Curve 2*x’, ’Curve 3*x’);

6.4 Subplots
You can divide a figure into multiple subplots using the subplot command. The syntax is:

subplot(rows, cols, pos)

- rows: Number of vertical subplots. - cols: Number of horizontal subplots. - pos: Position of the current subplot.

Figure 4: Subplot numbering order in MATLAB.

Example: Subplots in MATLAB

Example:
x = 0:0.01:10;
subplot(2, 3, 2);
plot(x, 2*x);
title(’Curve: 2*x’);
legend(’2*x’);

subplot(2, 3, 4);
plot(x, 3*x);
title(’Curve: 3*x’);
legend(’3*x’);

Figure 5: Example of using subplots to display multiple


functions.

6
Final Exercises: Testing Your Understanding
Exercise 1: Sum of Squares Using Loops
Write a MATLAB program to compute the sum of the squares of numbers from 1 to N , where N is provided by the user.
Perform the task using:
• A for loop
• A while loop
Verify that both versions give the same result.

Exercise 2: Create a Custom Function


Define a function in MATLAB that calculates the factorial of a number N . Save this function in a file named myFactorial.m.
Then, write a script that:
1. Prompts the user to input a number N .
2. Calls myFactorial to compute and display the factorial of N .

Exercise 3: Plot Multiple Functions


Write a MATLAB script to plot the following functions on the same figure over the range x = −10 to 10:

f1 (x) = x2 , f2 (x) = sin(x), f3 (x) = e−x

• Use different colors and line styles for each function.


• Add a title, labels for the axes, and a legend to distinguish the functions.

Exercise 4: Subplots for Visualization


Using the subplot function, create a MATLAB script that generates the following plots:
1. A plot of y = x2 in the first subplot.
2. A plot of y = sin(x) in the second subplot.
3. A plot of y = cos(x) in the third subplot.
Ensure all subplots have appropriate titles and labels for the axes.

Exercise 5: Matrix Operations with Nested Loops


Write a MATLAB script that:
1. Creates a 5 × 5 matrix where each element A(i, j) is the product of its indices, i × j.
2. Sets all diagonal elements to zero.
3. Displays the resulting matrix.

You might also like