TP04 Matlab
TP04 Matlab
Structures
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
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.2 Example
Suppose we want to fill a 3 × 3 matrix A such that:
A(i, j) = i + j
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.
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.
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
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.2 Examples
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:
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:
- rows: Number of vertical subplots. - cols: Number of horizontal subplots. - pos: Position of the current subplot.
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’);
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.