0% found this document useful (0 votes)
9 views71 pages

Computer Science Lab Course 3 Matlab PDF

This document presents the Matlab interface and its main features such as the command window, the workspace, the command history, the current folder, and help. It also introduces the basics of programming in Matlab.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views71 pages

Computer Science Lab Course 3 Matlab PDF

This document presents the Matlab interface and its main features such as the command window, the workspace, the command history, the current folder, and help. It also introduces the basics of programming in Matlab.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

DEMOCRATIC AND POPULAR ALGERIAN REPUBLIC

Ministry of Higher Education and Scientific Research

Nour Bachir El-Bayadh University Center


Institute of Sciences
Department of Technology

Course handout
UEM 2.1

MODULE TITLE

Computer Science 3
COURSE / TP

Dr. TADJEDDINE Ali Abderrazak (MCB)


Dr. BENDELHOUM Mohammed Soufiane (MCA)
Dr. BENDJILLALI Ridha Ilyas (MCB)

Nour Bachir University Center – El Bayadh

2022-2023
Preface

This course / lab manual, titled "Computer Science 3", is a methodological subject that is studied
by the students in 2thyear degree, semester 3, common exchange in sciences and technologies of all
the specialties. The program of this course/TP is designed to teach students a
fundamental understanding of programming and numerical calculation using Matlab.

Although the Matlab environment stands for MATrix LABoratory in English i.e.
matrix laboratory. MATLAB is a powerful computer programming language, which
you can use it as a calculator, and it's a good technique to try out ideas
that you could use in your program. However, when you have surpassed the step of
In experimentation, you generally rely on MATLAB to create a program that you
help to perform tasks: Regularly, Easy and Quick. These three characteristics do not...
do not say everything that MATLAB can do, but they provide you with ideas that you can
pursue and use to your advantage.

The disciplines of Science, Technology, Engineering, and Mathematics (STEM)


currently focusing on the topics of mathematical model simulation ahead
the experimentation. The innovation of all sorting requires these disciplines, as many do
practical professions. MATLAB has a rich and extensive toolbox for STIM that includes
Statistics, Simulation, Image Processing, Symbolic Processing, and Numerical Analysis.

Writing method
Suggestions for improving the course will be greatly appreciated. Although all precautions
measures had been taken to eliminate errors, it is very difficult to claim perfection. I will be
very grateful to the teachers and students and to the members of this course if they
report any error that may have slipped in.

In order to simplify learning for students, each lesson/TP sheet contains four parts:
1. The objective of the TP;
Cover the TP objective and the main ideas taught.
2. Part 01: Theoretical part (the Matlab interface);
The definitions of the commands and instructions used during the session.
3. Part 02: Simulation Part (MATLAB –SIMULINK);
Solved exercises including learning figures.
4. Part 03: Experimental part (MATLAB –SIMULINK).
Exercises to adapt to programming problems and the application of
notions targeted on parts 1 and 2.
Organization of TP sheets
According to the official framework, this course is divided into eight sheets:

TP No. The title Duration

TP 1 Presentation of a scientific programming environment (MATLAB) 1 week


TP 2 Displaying, reading, and saving data 2 weeks
TP 3 Script files and Data types and variables 2 weeks
TP 4 Vectors and matrices 2 weeks
TP 5 Control instructions (for and while loops, if statements and switch statements) 2 weeks
TP 6 Function files 2 weeks
TP 7 Graphics (Management of graphic windows, plot) 2 weeks

TP 8 Use of toolbox 2 weeks


Table of Contents
Pages
Foreword

TP Sheet: 01
1
Presentation of a scientific programming environment (MATLAB)
Lab Sheet: 02
9
Reading, displaying and saving data
TP Sheet: 03
14
Script files and data types and variables
Lab Sheet: 04
21
Vectors and matrices
TP Sheet: 05
29
Control instructions (for and while loops, if and switch statements)
TP Sheet: 06
34
Function files
Lab Sheet: 07
39
Graphics (Management of graphic windows, plot)
Lab Sheet: 08
55
Use of toolbox
Bibliography 67

I–
Lab Sheet: 01
Presentation of a programming environment
scientific (MATLAB)
Fiche TP : 1 Presentation of a scientific programming environment (MATLAB)

Nour Bachir El-Bayadh University Center


Institute of Sciences
Department of Technology
Spécialité :HYD, GC, ETT, ELN et TLC
Level: Bachelor's 02 (semester 03)
Practical Computer Work 3

TP 01: Presentation of a scientific programming environment (MATLAB)

The objective of the lab:

This TP01 and TP02 aims to familiarize you with the interface and the basics of
the MATLAB environment in order to use some basic functions for reading,
the display and saving of data.

Part 01: Theoretical part (the Matlab interface)


We will familiarize ourselves with the Matlab interface. Depending on the version used, the interface
may change slightly but the central points will remain the same.

Command Windows
A scalar variable (x=5: assigning the value 5 to the variable x) is seen by MATLAB.
like a matrix of dimension 1x1 (row x column). As shown in the following example
in which we assign the value 5 to the variable x and then ask for its dimensions by the
function ( ) in the Command Window space:

Course/Practical: Computer Science 3 -2- Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 1 Presentation of a scientific programming environment (MATLAB)

>> x=5
Use of semicolon (answer)
>> size(x)

In order to avoid the display of Matlab defines a


results, just follow the variable, it is
command by a semicolon a matrix of size
(;). 1x1 (one line by one)
column).

A command This command clears the Command Window screen.


see a clean window. A command This command allows you to delete
all the variables in the Workspace space to redistribute on a
clean window.

Workspace (go to Window -> Workspace)


In this window, we get the list of variables known to Matlab. It is
It is possible to double-click on a variable to display it. A right-click on the
variables give many options such as: Copy, Paste, Delete
etc.

Command History (go to Window -> Command History)


The Command History space keeps a record of all the
operations that were carried out in the Command Window space. On
can also move up the order list by positioning oneself
in the Command Window and by pressing the arrow keys
↑ ↓.

Current Folder (go to Window -> Current Folder)


It is the folder that contains the script file, the programming, the work done on
Matlab.

Course/Lab: Computer Science 3 -3- Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 1 Presentation of a scientific programming environment (MATLAB)

Help
The help space is essential when programming with a high-level language.
like Matlab, where the number of functions is very important and the syntax is sometimes
complex. To access help, you can either select a function and press F1 on
the keyboard, or type in the space Command Window: help cos, help input... etc. It is
It is essential that you familiarize yourself with Matlab's help tools to succeed in this.
Course/TP.

Command Description
open a window containing the list of Matlab commands as well
helpwin
their documentation

help give the list of all commands by themes

help me describe the function name.m

look for name Search for an instruction using the keyword name
Use: help Product Help to display the help Window

Script
The script is the file with the ‘.m’ extension that contains the program more simply. It
This is a list of commands and functions.

Function
A function will allow entering input arguments and obtaining output.ffdifferents
output variables.

Editor
Most of your work in Matlab will involve creating or modifying files with
.m extension which defines Matlab files. When performing a task in
In Matlab, it is often possible to do it using only the Command Window.
However, when this task becomes more complex (several dozen lines of code)
or that we wish to be able to pass it on to someone else easily, we use the
editor window. A .m file is created which can be either a script or a function.

Course/TP: Computer Science 3 -4- Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 1 Presentation of a scientific programming environment (MATLAB)

Part 02: Simulation Part (MATLAB–SIMULINK)


To start, we set the USERPATH, the folder that contains your file (.m)
Create a folder on the Desktop named: TP_INFO3.
Create another folder in the previous folder with the name: TP01_02_INFO3.
In the Current Folder space, select the folder TP01_02_INFO3 for 1heTP and
and so on for the other labs.

Exercise 1: 'Hello World'


This is a brief program to set up the diffdifferent necessary elements.
Then create a new script (.m) in the folder TP01_INFO3.
Write in 1eraline :
1.varibale='Hello world';
Run
Save the file as hello.m.
Run
Conclude!

Exercise 2: 'Sum of two numbers'


We will try to create a script here to make a function that takes two numbers.
takes input and returns the sum of the two.
Create a new script file (Ctrl + N).
Create a program that will calculate the sum of two numbers.
Save with the file name: Som_xy_TP1.m (use the underscore "_" and
non " - " )

What do you notice?

Exercise 3: 'Sum of two arbitrary numbers'


We want a function that takes two random numbers as input and returns by displaying.
the sum of the two.
Create a new script file (Ctrl + N). Name it: Som1_TP1.m, Save !!
Write the function:

Course/TP: Computer Science 3 5 Dr. Ali Abderrazak TADJEDDINE


Lab sheet: 1 Presentation of a scientific programming environment (MATLAB)

Run
An error is displayed:

We defined a function Som1_TP1(x,y) with two arguments, but


the function was called without arguments; so to correct this
Error: you must provide a value for x and y when calling the function.
Som1_TP1 in the Command Window space: It is noted
that Matlab displayed the variable since we did not use the semicolon and the
default variable.

Exercise 4: 'How to find the desired information'


Use the Command Window
help log
help mod

Exercise 5: 'Sum of two arbitrary numbers by choice'


We want to create a program that takes three digits as input choice and returns a
display of product of the first digits and the root of product of the last numbers.
Create a new script file (Ctrl + N), name it: Som2_TP1.m, Save !!
Write the function:

Four functions were used: 'input()', 'sqrt()', 'dips()', and 'fprintf()'.


Use 'help input()' to discover these functions.
What is the purpose of these functions?

Course/TP: Computer Science 3 6 Dr. Ali Abderrazak TADJEDDINE


TP file: 1 Introduction to a scientific programming environment (MATLAB)

Section 03: Experimental Part (MATLAB–SIMULINK)


Exercise 5: 'Enter First Name and Last Name'
We will try here to create a script to make a function that takes 2 arguments.
your first and last name entered and return your first and last name on the same line
exit.
Create a new script file (Ctrl + N). Name it: Name_TP1.m, Save !!

Exercise 6: "Enter First Name and Last Name + the overall average of the 1erayear
We are going to create a script for a function that takes 3 arguments: your first name and last name and

the average grade of the 1st year as inputs and returns your first and last name
and the average on the same line in output.
Create a new script file (Ctrl + N). Name it: Name1_TP1.m, Save !!

Course/TP: Computer Science 3 -7- Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 02
Reading, displaying, and saving data
TP File: 02 Lecture, display and saving of data (MATLAB)

Nour Bachir El-Bayadh University Center


Institute of Sciences
Department of Technology
Spécialité :HYD, GC, ETT, ELN et TLC
Level: Bachelor's Degree 02 (semester 03)

Computer Practical Work 3

TP 02: Reading, displaying, and saving data

The objective of TP:


This TP01 and TP02 aims to familiarize you with the interface and the basics of
the MATLAB environment in order to use some basic functions for reading,
the display and saving of data.

Part 01: Theoretical part (the Matlab interface)


We will familiarize ourselves with the Matlab interface. Depending on the version used, the interface
may change slightly but the central points will remain the same.

Command Windows
A scalar variable (x=5: assigning the value 5 to the variable x) is seen by MATLAB
like a matrix of dimension 1x1 (row x column). As shown in the following example
in which we assign the value 5 to the variable x and then ask for its dimensions by the
function ( ) in the Command Window space:

Course/TP: Computer Science 3 8 Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 02 Reading, displaying, and saving data (MATLAB)

>> x=5
Use of semicolon (answer)
>> size(x)

In order to avoid the display of Matlab defines a


results, just follow the variable, it is
commanded by a semicolon a matrix of size
(;). 1x1 (one line per one)
column).

A command This command clears the Command Window screen.


see a clean window. An order This command allows you to delete
all the variables in the Workspace space to start again on a
clean window.

Workspace (go to Window -> Workspace)


In this window, we obtain the list of variables known by Matlab. It is
It is possible to double-click on a variable to display it. A right-click on the
variables give many options such as: Copy, Paste, Delete
etc.

Command History (go to Window -> Command History)


The Command History space keeps a record of all the
operations that were carried out on the Command Window space. On
can also move up the order list by positioning itself
in the Command Window and by pressing the arrow keys
↑ ↓.

Current Folder (go to Window -> Current Folder)


This is the folder that contains the script file, the programming, the work done on
Matlab.

Course/Practical: Computer Science 3 9 Dr. Ali Abderrazak TADJEDDINE


Fiche TP : 02 Reading, displaying, and saving data (MATLAB)

Help
The help space is essential when programming with a high-level language.
like Matlab, where the number of functions is very important and the syntax is sometimes
complex. To access help, you can choose a function and press F1 on
the keyboard, or type in the space Command Window: help cos, help input… etc. It is
It is essential for you to familiarize yourself with the help tools in Matlab to succeed in this.
Course/TP.

Command Description
open a window containing the list of Matlab commands as well as
helpwin
their documentations

help give the list of all commands by themes

help name describe the function name.m

look for name Search for an instruction using the keyword name
Use: help Product Help to display the help Window

Script
The script is the file with the '.m' extension that contains the program more simply. It
This is a list of commands and functions.

Function
A function will allow entering arguments as input and obtaining diffdifferent
output variables.

Editor
Most of your work in Matlab will involve creating or modifying files with
.m extension that defines Matlab files. When performing a task under
In Matlab, it is very often possible to do it using only the Command Window.
However, when this task becomes more complex (several dozen lines of code)
or when we want to be able to transmit it to someone else easily, we use the
Editor window. A .m file can be created either as a script or a function.

Course/TP: Computer Science 3 10 Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 02 Lecture, affichage et sauvegarde des données (MATLAB)

Part 02: Simulation Part (MATLAB–SIMULINK)


To begin, we set the USERPATH, the folder that contains your file (.m)
Create a folder on the Desktop named: TP_INFO3.
Create another folder in the previous folder named: TP01_02_INFO3.
In the Current Folder space, select the folder TP01_02_INFO3 for the 1heTP and
and so on for the other TPs.

Hello World
This is a brief program to set up the slides.ffdifferent necessary elements.
Then create a new script (.m) in the folder TP01_INFO3.
Write in the 1eraline:
1.variable='Hello world';
Run
Save the file with the name hello.m.
Run
Conclude!

Exercise 2: 'Sum of two numbers'


We will try here to create a script to make a function that takes two numbers.
takes in two numbers and returns their sum.
Create a new script file (Ctrl + N).
Create a program that will calculate the sum of two numbers.
Save with the file name: Som_xy_TP1.m (use the underscore character "_" and
non " - " )

What do you notice?

Exercise 3: 'Sum of two arbitrary numbers'


We want a function that takes two random numbers as input and returns by display.
the sum of the two.
Create a new script file (Ctrl + N). Name it: Som1_TP1.m, Save!!
Write the function:

Course/TP: Computer Science 3 11 Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 02 Lecture, display and save data (MATLAB)

Run
An error is displayed:

We defined a function Som1_TP1(x,y) with two arguments, but


the function was called without arguments; so to correct this
Error: you must provide a value for x and y, we call it in the function.
Som1_TP1 in the Command Window space: It is noted
that Matlab displayed the variable since we did not use the semicolon and the
default variable

Exercise 4: 'How to find the desired information'


Use the Command Window
help log
help mod

Exercise 5: 'Sum of two arbitrary numbers by choice'


We want to create a program that takes three digits as input and returns a
display of the product of the first digits and the root of the product of the last numbers.
Create a new script file (Ctrl + N), name it: Som2_TP1.m, Save !!
Write the function:

We used 4 functions: "input(), sqrt(), dips() and fprintf()".


Use the 'help input()' to discover these functions.
What is the purpose of these functions?

Course/TP: Computer Science 3 12 Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 02 Reading, displaying and saving data (MATLAB)

Part 03: Experimental part (MATLAB–SIMULINK)


Exercise 5: 'Enter Last Name and First Name'
We are going to try here to create a script to make a function that takes 2 arguments
your first and last name in input and return your first and last name on the same line
exit.
Cree un fichiernew script(Ctrl +N). Nommer :Name_TP1.m, Sauvegarder !!

Exercise 6: 'Enter First Name and Last Name + the general average of 1'erayear
We are going to create a script for a function that takes 3 arguments: your first name and last name and

the overall average of the 1st year like the entries and returns your name and surname
and the average on the same line in output.
Create a new script file (Ctrl + N). Name it: Name1_TP1.m, Save!!

Course/TP: Computer Science 3 - 13 - Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 03
Script files and Types of data and variables
Lab Sheet: 03 Script files and types of data and variables

Nour Bachir El-Bayadh University Center


Institute of Sciences
Department of Technology
Spécialité :HYD, GC, ETT, ELN et TLC
Level: Bachelor 02 (semester 03)
Computer Practical Work 3

TP 03: Script files and Types of data and variables

The objective of the TP:

This TP03 aims to introduce you to basic operations as well as types of variables.
their uses in solving exercises.

Part 01: Theoretical Part (Data and Variable Types)


Basic tools
It has already been said, the basic principle of Matlab is to consider most objects as
matrices. Thus the usual operations+, −,∗,/ must be understood as operations
matrix.
We will dedicate the next section to these operations. First, we will look at this.
what happens for 1x1 matrices (that is to say a single element).

Types of variable data


There are five main types of variables in Matlab:
NUMBERS (integers, reals, complexes)
CHARACTERS (the character strings),
LOGIC (1 or 0).
Let's define a variable of each type:

The variable 'a' represents a real number, b a complex number, c a string, d1 and d2 are two
ways to define a logical variable (TRUE in this case) and e is an integer encoded on 8 bits.
We can then check the type of these different variables using the function :

Use the functions ( ), (… ), (…


. )
Conclude !!

Course/TP: Computer Science 3 - 14 - Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 03 Script files and Data types and variables

MATLAB Variables
Variable and function names are made up of letters and numbers. Matlab distinguishes them.
between uppercase and lowercase letters, i.e. INFO3, info3, and Info3 are different variables. If the
the variable already exists, the content is overwritten by a new value assigned to this variable.

Variable :
In Matlab, there is only one data type: the matrix type.
Matrix Vector Scalar
m x n, m, n > 1 1 x n, n > 1, 1x1

Names or strings of characters:


Variable name Names 1, 2, 3, …
strings 1, 2, (1+i)…. strings

Classes and Format


By the syntax introduced above, MATLAB defines variables that belong to the class
double array, that is to say real arrays that can correspond to scalars,
vectors or matrices. Aside from this fundamental class, it should be noted that there are other
predefined MATLAB classes. The most important is certainly char array, to which
belong to the strings, defined using '...'.

Format and Coding


The following table lists the characters and the available conversion subtypes in MATLAB.

We will use the coding of the following formats for our practicals:
Format Declaration of Format Declaration of
Numbers Character
Conversion variable Conversion variable
the integers %d intvariable Single %c
charvariable
the reals %f float variable String %s

Course/TP: Computer Science 3 15 Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 03 Script files and Types of data and variables

Classes
Double / single character
Display format
By default, Matlab displays results in decimal format. This format can be changed at any time.
moment with the function
Order Display Example
short format five-digit decimal 31.416
long format decimal to 16 digits 31.41592653535879
bank format fixed comma to 2 decimal places 31.41
format rat fractional 3550/113

Arithmetic and operations on scalars


We have already performed basic operations with variables and functions in TP02, you can
test the following examples:

One can also work on Matlab as a numerical calculator using the functions
trigonometric, power, logarithmic etc.

Main mathematical function used in Matlab

Course/TP: Computer Science 3 16 Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 03 Script files and Data types and variables

Part 02: Simulation Part (MATLAB–SIMULINK)


Create a new folder in the folder TP_INFO3 with the name: TP03_INFO3.
Change Current folder (path) to TP03_INFO3 in Matlab.

Exercise 01
Create a program that calculates the sum from 1 to 10. = + +⋯+ )
Create new script (Ctrl + N). Save with the file name: Som_TP3.m

Exercise 02
Look for a program that allows you to achieve the product of 3 to 7.P = 3 * 4 * ... * 7)
Create new script (Ctrl + N). Save with the file name: Prod_TP3.m

Exercise 03
Create a program that calculates the square root of a number.
Create new script (Ctrl + N). Save with the filename: Rac_TP3.m

Exercise 04
We are looking for a program that calculates the determinant.∆= 2-4acof a polynomial
of order 2.
Create a new script (Ctrl + N). Save with the file name: Det_TP3.m

Exercise 05
Implement a function that calculates the two solutions of a polynomial equation
of 2emeorder based on the 3 coefficients (a, b, c).
Create new script (Ctrl + N). Save with the file name: 2ordr_TP3.m

Let the polynomial of order 2 be the following: ( =


) +28x + 16The coefficients of the polynomial are:
P=[1, 8, 16]
In general, a polynomial of degree 2 is written as: (= ) + 2 + with P=[a, b, c] and
− ± √ 2 -4
the roots are: =
( () − )( 1− 2) with =1,2
2

We are looking to use a Matlab function to solve the second-order polynomial:


Create new script (Ctrl + N). Save with the filename: 2ordr1_TP3.m
Use the same coefficients proposed in the previous section,
Use the function () to solve the polynomial equation.

Course/TP: Computer Science 3 - 17 - Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 03 Script files and Data types and variables

Compare the results obtained with your program results, Conclude!


Use the function () to construct the coefficients of a polynomial from
these roots

Exercise 06
Let the following polynomial:
7 6 5 4
( )= -37x+ 555x - 4295x + 17924x -37668x 3 + 30240x 2

Create new script (Ctrl + N). Save with the file name: Pol_TP3.m
Using Matlab;
ResolveP(x) = 0.
Calculate the polynomial ( ) for = 2, x = 3.(use the function ( , ))

Exercise 07
Let the roots of a polynomial be:
R = [7,8, 9, 5, 02,6]
Create new script (Ctrl + N). Save with the file name: RacPol_TP3.m
Using Matlab;
Find the coefficients of the polynomial.
What is the order of the polynomial?
Calculate the derivative of the polynomial function (use the function ( ))
Calculate the primitive of the polynomial function (use the function ( ))

Exercise 08
Consider the following polynomials:

) = 3 + 3x2 -24x - 80and = ( )− −2 20 and = x( +) 4


1( 2 3

Create new script (Ctrl + N). Save with the file name: divPol_TP3.m
Find the coefficients of the polynomials.
Using Matlab;
calculate the roots of 1 (and
) 2 (. )
Calculate the product of convolution ℎ( ) = 2 ( )∗ 3( ).use the
function ( , ))

Course/TP: Computer Science 3 - 18 - Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 03 Script files and data types and variables

Calculate the deconvolution productℎ = 2( )∗ 3( )(. use ( )the


function ( , )
Conclude

Exercise 09
Create new script (Ctrl + N). Save with the filename: nbrcmplx_TP3.m
Enter the following complex numbers:

1= 1+ , 2=
2,
3=
/4

However, i and j are reserved MATLAB variables for the index of complex numbers.
Calculate the following quantities using Matlab:
La partie réelle des nombres complexes, affecter chaque partie à une variable.
The imaginary part of complex numbers, assign each part to a
variable.
The conjugate of 1 3.

The modulus of each number is assigned to another variable.


The argument of each complex number.
Use complex functions in the Main mathematical function used in Matlab.

Part 03: Experimental part (MATLAB–SIMULINK)


Exercise 10 of preparation (for online teaching)
Create new script (Ctrl + N). Save with the file name: EX10_TP3.m
1. Evaluate the following quantities in Matlab with 5 significant figures:

2. Calculate − . [ ] Comment on the result.


3. Calculate until the 15thththisffsignificant results. Which is the greatest?
4. Compare the right division '/' and the left division '\'. Comment. (Use ALTGR)
+ 8 for '\'
5. Find the real and imaginary parts of the following complex numbers:
( 3 +4) 1
and andln( −1)
1+
6. Calculate the modulus and the argument of the following complex numbers:

Exercise 11
Create new script (Ctrl + N). Save with the file name: EX11_TP3.m

Cours/TP : Informatique 3 19 Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 03 Script files and Data types and variables

Let the following polynomial be:


5 4 3
( )= −2 − 8x + 16x +2 16x - 32
Evaluate the values of ( ) for the pointsx = 0, x = 1, = 2.
Calculate the derivative of ( )
Calculate the antiderivative of ( )
( )
Calculate the polynomial of order 2 ( ) as such ( )= 3-6 2
+12 -8

Course/TP: Computer Science 3 - 20 - Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 04
Vectors and matrices (MATLAB)
TP Sheet: 04 Vectors and matrices (MATLAB)

Nour Bachir El-Bayadh University Center


Institute of Sciences
Department of Technology
Spécialité :HYD, GC, ETT, ELN et TLC
Level: Bachelor's 02 (semester 03)
Computer Practical Work 3

TP 04: Vectors and matrices

The objective of the lab:

This TP04 aims to introduce you to operations on vectors and matrices in order to
use them for solving the exercises.

Part 01: Theoretical part (Vectors: Lists and arrays)


Matlab primarily uses lists (vectors) or arrays (matrices) for computation. It is
It is useful to know how to handle these objects from now on.

In Matlab, a variable (a; x; ...) or a list of numbers is a special array.


It can be noted, to simplify, that in Matlab everything is a matrix (a matrix is a
tableau). If this may seem strange at first, it is what allows Matlab to be as
powerful and fast in calculation.

Construction of a Vector (a list)


One can define a list of numbers by giving its elements in sequence separated by
spaces or commas. The list is enclosed by brackets [] .
The difference between comma, space, and semicolon

Vecteur à 3 élémentshorizontalesVecteur à 3 élémentsverticales

The variable is considered as a table containing a 1 8 16


line and three columns:

Course/TP: Computer Science 3 21 Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 04 Vectors and matrices (MATLAB)

Transpose of a vector
The transpose to go from a row to a column or vice versa:
vec1= [1 4 7]
>> vec1’

Manipulate a vector
Accessing elements of a list
We can extract elements from a vector. We access the element at index k.
the list has ( ).
We are looking for example the 3.thvalue of vectorP:P(3)

Example1
Let: ( )= − − + + −
The vector of the coefficients of the polynomial 2 (is)defined by: P2=[1 -2 -8 16 -32]

We are looking for example for the 2.thvalue of We are looking for the first 3 values of the vector.

vector of P2: 2(2) deP2: 2(1: 3)

We are looking for the values of the odd indices of vector deP2: 2(1: 25)

The expression( ∶ ∶ ) create a list whose elements go from à with a step of .


When no step is given, the default value of the step is 1. Accessing an element
A negative indicator leads to an error.

The size of a vector


The order () allows you to return the number of elements in a vector.

Course/TP: Computer Science 3 22 Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 04 Vectors and matrices (MATLAB)

Concatenate two vectors


P3 = [P2 vector1]

Command linspace()
( , , )generates: N points between X1 and X2, for N = 1, linspace returns
X2.
4= (1,10,10)

Construction of a matrix (an array)


You can create arrays of numbers with multiple rows by giving each row
separated by a semicolon(; ).
Let:P3 = [1 − 2- 8 16- 32; 123 4 5

Access to the elements of a matrix (an array)


Similarly, we can extract parts of a matrix. The first number indicates the row and
the second number the column.

Example2
Find the value of element (1,3) of the matrix P3: ( , )
Find the values of the 4thcolumn (X,4) of the matrix P3: (: , )
Find the values of 2emeline (2,X) of the matrix P3: ( , )
Look for the values of the 1eraline from 3emecolumn of the matrix P3 :
( , : )

Change of an element in the matrix


We want to modify the value of element (1,3) to 100: P3(1,3) = 100.

Course/TP: Computer Science 3 23 Dr. Ali Abderrazak TADJEDDINE


Lab sheet: 04 Vectors and matrices (MATLAB)

Otherwise, in the Workspace space, double-click on the P3 matrix (variable


Editor), find the element (row 1, column 3), change it to the value 100.

Part 02: Simulation Part (Operations on Matrices (arrays))


Create a new folder in the TP_INFO3 folder with the name: TP04_INFO3.
Change Current folder (userpath) to TP04_INFO3 in Matlab.

All standard operations between matrices and vectors are available (addition,
multiplication, transposition, etc.). Matlab also allows applying the main
element-wise operators, it is generally enough to prefix the desired operator with
a point '. '

Let the two matrices A and B be as follows:


8 1 6 4 12 5
8 1 ), ( )4,
=( 3 5 7 ) , A1 = ( 6 1 6) , =( 1= =2 ( 21 6 ), 3 =
5 7
4 92 3 3 1 6
(4 9 ),

Exercise 1 (Concatenate, Compare the matrices)


Using Matlab (Command Window space);
Matrix C includes matrix A and A1 horizontally: C = [A, A1]
Use the function ( , , ) to assemble matrices A and A1: C1=cat(2,
A, A1)
Compare the matrix C and C1, use the function: ( , )
Compare matrix A and A1, use: A == A1
Conclude !!

Exercise 2 (Add–Remove (row/column) in a matrix)


Using Matlab (Command Window)
Calculate the dimension of matrix A and B.
Calculate the number of elements in the vectors V1 and V2.
Add vector V1 in the 3soulcolumn of matrix B.

Method 1 Method 2

Course/TP: Computer Science 3 24 Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 04 Vectors and matrices (MATLAB)

Add vector V2 in 3.emeline of matrix B.

Remove the second row of matrix A and assign the new matrix to C3.

Method 1 Method 2

Exercise 3 (Summation - product–transposition–square matrix)


Create a new script (Ctrl + N). Save with the name: EX3_TP4.m
Introduce the matrices in the script.
Check the matrices by running the program .
Calculate the dimensions ofA, A1, B, V1, V2et V3.
Calculate the transpose matrix of A and B: transpose(A), B'.
Calculate the square matrix of B: B^2.
From matrix A, extract the submatrix 2(3.5; 4.9)
Calculate the sum of matrices A and A1:S = A + A1;
Calculate the sum of matrices B and A2: = + 2;
Calculate the sum of matrices A and C3:Sopm1 = A + C3;

To calculate the sum of the two matrices, the dimensions of the matrices must be the same.
same ones.
Calculate the product of matrices A and V1:prd = A * V1;

Course/TP: Computer Science 3 - 25 - Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 04 Vectors and matrices (MATLAB)

Check the result manually.

For the product, the dimension of the column of the first matrix must equal to the
dimension of the line of the second matrix( , ) ∗ ( ’, ’) ≫ = ’

Exercise 4 (special matrices)


Using Matlab (Command Window space);
Matrice d’identité : utiliser la commandeeye(n,m) : 1)(n=3,m=1),2)(n=3,m=2),3)
(n=3,m=3).
Null matrix: use the command zeros(n,m): 1)(n=3,m=1), 2)(n=3,m=2), 3)
(n=3, m=3).
Unit matrix: use the command ones(n,m): 1)(n=3,m=1),2)(n=3,m=2),3)
(n=3,m=3).
Matrice aléatoire : utiliser la commanderand(n,m) :1)(n=3,m=1),2)(n=3,m=2),3)
(n=3,m=3).
Magic Matrix: use the command magic(n).
Exercise 5 (introduce a matrix (2,2))
Create a new script (Ctrl + N). Save with the name: EX5_TP4.m
Create a function that takes 4 numbers as input and returns a matrix as output.
(2,2).
Use the command zeros(n, m) to initialize the matrix (2,2).

Exercise 6 (input a (2,2) matrix from the user)


Create a new script (Ctrl + N). Save with the name: EX6_TP4.m
Create a function that takes 4 numbers as input from the user and returns
11 12
output a matrixF1(2,2). F1 =( )
21 22
Use the command 11Input ('enter the 1st number')
Use the command ( , ) to initiate the matrixF1(2,2).

Exercise 7 (introduce a (3,3) matrix by the user)


Create a new script (Ctrl + N). Save with the name: EX7_TP4.m
Create a function that takes 9 numbers as input from the user and returns in
output a matrix 2(3,3).
Use the command vera11=input('enter the 1hename ');
Use the command ( , ) to initiate the matrix 2(3,3).

Course/TP: Computer Science 3 26 Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 04 Vectors and matrices (MATLAB)

Exercise 8 (Matrix Summation(2,2) + Matrix(2,2) by choice)


Create a new script (Ctrl + N). Save with the name: EX8_TP4.m
We are looking to create a function that performs the summation between two + .

Exercise 9 (Matrix(3,3) x Vector(3,1) by choice)


Create a new script (Ctrl + N). Save with the name: EX9_TP4.m
We are looking to create a function that multiplies a (3,3) matrix and a
vector(3,1) entered by the user and displays the result.
Use the command b11=input('enter the 1hename ');
Use the command ( , ) to initiate the matrix 2(3,3).

Exercise 10 (solve a linear matrix system AX=Y)


Create a new script (Ctrl + N). Save with the name: EX10_TP4.m
Create a function that solves the matrix equation = and display in output
the result of X, with the matrix A(3,3), the vectors Y(3,1), X(3,1).
Measure the program execution time in seconds; use command tic; and
toc;
Use the command a11=input('enter the 1hename ');
Use the command ( , ) to initiate the matrixA(3,3).
Use the command ( , ) to initiate the vectorX(3,1).
Use the command ( , ) to initiate the vectorY(3,1).
Section 03: Experimental part (MATLAB–SIMULINK)
Exercise 11 of preparation (determinant of a matrix)
Create a new script (Ctrl + N). Save with the name: EX11_TP4.m
Create a function that returns the determinant of a matrix ( , ) given by
the user.
Use the command var11=input('enter the 1hename ');
Use the command ( , ) to initiate the matrix (2,2).

Exercise 12 of preparation (inverse of a matrix (2,2))


Create a new script (Ctrl + N). Save with the name: EX12_TP4.m
Create a function that inverts a matrix ( , ) provided by the user.
Use the command a11=input('enter the 1ername ');
Use the command ( , ) to initiate the matrix (2,2).

Exercise 12 of preparation (inversion of a matrix (3,3))


Create a new script (Ctrl + N). Save with the name: EX12_TP4.m
Create a function that inverts a matrix ( , ) given by the user.
Use the command G11=input('enter the 1ername ');
Use the command ( , ) to initiate the matrixG(3,3).

Course/TP: Computer Science 3 - 27 - Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 04 Vectors and matrices (MATLAB)

Course/TP: Computer Science 3 28 Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 05
Control instructions (Instructions: if & switch)
TP Sheet: 05 Control instructions (Instructions: if & switch)

Nour Bachir El-Bayadh University Center


Institute of Sciences
Department of Technology
Spécialité :HYD, GC, ETT, ELN et TLC
Level: Bachelor's Degree 02 (semester 03)

Computer Practical Work 3

TP 05: Control instructions (Instructions: if & switch)

The objective of the lab:

This TP05 aims to introduce you to control instructions and conditions.


Conditional structure allows executing an action if and only if a prior test is met.
returns the value 'TRUE'.

Part 01: Theoretical part (Conditional Statements: if & switch)


There are two possible commands for performing condition tests on the
data.
The instruction () allows testing the value of a variable and performing different
treatments based on the tested cases.
The instruction () allows you to choose between different cases, and to match a
treatment tailored to each of the recognized cases.

Comparison operators and logical operators are primarily used in


the control instructions:
Comparison operators Logical operators
(relational) And : & : (X & Y)

Strictly greater: (X > Y) Or: (X | Y)

Strictly less than: (X < Y) Not : X (-X)

Compare two objects: (X == Y)


Greater than or equal to: (X >= Y)

Less than or equal to: (X <= Y)


Different from: (X~=Y)

The instruction ... ... ...


Execute instruction or a group of instructions if the
the condition is true.

& are optional and do not execute the instructions


that when the previous expressions of the block are false.
A block can include several instructions .

Course/TP: Computer Science 3 29 Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 05 Control instructions (Instructions: if & switch)

A logical expression is an expression whose result can be true or false (data


logic);
Sequence of instructions (statements) is the processing to be carried out if the expression

logic is true.

Description
Expressions can include relational operators (such as < or ==) and
logical operators (such as &&, || or ~). MATLAB evaluates expressions composed of
left to right, respecting the rules of operator precedence.
You can use any number of if statements, each if statement
requires end.
Avoid adding a space in elseif (else if). The space creates a new statement.
if nested which requires its own end keyword.

Example 1 (If-Else-End conditioned instructions)


Create a new folder named TP05_INFO3 in the folder TP_INFO3.
Change Current folder (userpath) to TP05_INFO3 in Matlab.
Create a new script (Ctrl + N). Save with the name: Exemple1_TP5.m
Assign the following values (5, 1, 10/2) to the successive variables (a, b, c):

Description: Script :
The lines (1,2,3): Initiation
Initialization of variable values.
Lines (5 to 8): test
The if statement: tests if the variable a is different from c
(value !!)
10
Please value ofa = 5is different from ==5
2

So calculate:
the new value of = ( = + )= + =
disp('b='): display in the space the expression: b=
display(b): show the value of b: 2;
Lines (9 to 14): against the test
The else statement: 'tests if variable a is equal to c'

Not the value of = is equal to ==

So:
display(a), display(c): display in the space the value of
the variable a and c.
b = b - 1: calculate the new value of b and assign it to b
disp('b='): display in the space the expression: b=

Course/TP: Computer Science 3 - 30 - Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 05 Control instructions (Instructions: if & switch)

display(b): show the value of b: 0;


The line (15): end
The instruction end: terminates and closes the if condition.

Example 2 (Conditioned instructions if-elseif-end)


Create a new script (Ctrl + N). Save with the name: Exemple2_TP5.m
We are looking for a function that displays a square matrix of size n; such as zeros(),
ones() or rand() depending on the input 1 or 2 or 3.
Use the instruction .

The instruction () . . . ... ...


The switch statement executes conditionally a
set of instructions among several choice numbers,
chains, objects. Each choice is a case.

A 'switch_expression' to test a scalar or a


string. The switch block tests
each case until one of the cases is true.
If this case is true, MATLAB executes the corresponding instructions, then exits the
switching block.
Otherwise, it executes only when no case is true.

Course/Practicals: Computer Science 3 - 31 - Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 05 Control instructions (Instructions: if & switch)

Example 3 (Conditional Instructions, Numbers : … … )


Create a new script (Ctrl + N). Save with the name: Exemple3_TP5.m
We are looking for a function that displays a square matrix of size n either zeros() or ones()
or rand() depending on inputs 1 or 2 or 3.
Use the instruction .

Part 02: Simulation Part (Conditions)


Exercise 1 (test of a real variable: if)
Create a new script (Ctrl + N). Save with the name: EX1_TP5.m
Create a function that tests a real variable a to see if it is positive, zero, or negative and
redone by display.
Use the if statement.

Exercise 2 (testing a real variable: switch)


Create a new script (Ctrl + N). Save with the name: EX2_TP5.m
Create a function that tests a real variable a if it is positive, zero, or negative and
returns by display.
Use the switch statement.

Exercise 3 (Saving a file)


Create a new script (Ctrl + N). Save with the name: EX3_TP5.m
Create a function that displays "Do you want to save? type Y or N:" and it
displays the recording or cancellation of the file.
Use the if statement.
Reuse the switch instruction.

Course/TP: Computer Science 3 - 32 - Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 05 Control instructions (Instructions: if & switch)

Part 03: Experimental part (MATLAB-SIMULINK)


Exercise 4 (checking the inversion of a matrix)
Create a new script (Ctrl + N). Save with the name: EX4_TP5.m
Create a random matrix of size 3. = ( );
Create a function that returns the inverse of a matrix if possible, or
inverse error if the determinant of a matrix equals 0.
Use instruction:
Use instruction: ( )
Use instruction:error of inversion
For the test: Use the following square matrix: = [2, 4, 6; 3, -8, -5; 5, -4,1].
Preparation exercise 5 (Add the matrix inversion test to
the EX12_TP4
Create a new script (Ctrl + N). Save with the name: EX5_TP5.m
Copy the script from the exercise EX12_TP4.md into the script of EX5_TP5.
Modify the script by adding the function that returns the inverse test of a
matrix if possible or inversion error if the determinant of a matrix
equal to 0.
Use instruction: switch.
For the test: Use the following square matrix: = [ , , ; , − , − ; , − , ].

Exercise 6 of preparation (Add a test for polynomial 2thdegree)


Create a new script (Ctrl + N). Save with the name: EX6_TP5.m
Copy the script from exercise 2ordr_TP3.md into the script of EX6_TP5.
Let's create a program that finds the roots of a quadratic equation. ^2+
+ = 0 with the conditions of the discriminant.

Course/TP: Computer Science 3 - 33 - Dr. Ali Abderrazak TADJEDDINE


TP sheet: 06
Control Instructions (Loop: for & while)
Lab sheet: 06 Control instructions (Loop: for & while)

Nour Bachir El-Bayadh University Center


Institute of Sciences
Department of Technology
Spécialité :HYD, GC, ETT, ELN et TLC
Level: Bachelor's 02 (semester 03)
Practical Computer Work 3

TP 06: Control instructions (Loop: for & while)

The objective of the practical work:

This TP06 aims to familiarize you with control instructions as well as operations on the
loops, this last one allows you to repeat the same command a large number of times.
times by varying a parameter.

Part 01: Theoretical part (Loop: for & while)


The instruction: ...
The instruction (to) execute one/multiple MATLAB instructions in a loop of
repetition with one/multiple conditions. It is more practical for the definition of sequences by
recurrences as we will see.

Body of the loop


Index: is a variable called the index of the
loop;
Lower_bound and Upper_bound: are two constants
real (called loop parameters);
Sequence of instructions: is the processing to be carried out for the index values
variant between lower_bound and upper_bound with an increment of 1.

To force an immediate exit from the loop, use a statement


.
To traverse the values of a single column vector, transpose it first to
create a row vector.

Example 1
Create a new script (Ctrl + N). Save with the name: Exemple1_TP6.m
Create a Matlab function that counts from 1 to 10.
Use instruction: for.

Course/TP: Computer Science 3 - 34 - Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 06 Control instructions (Loop: for & while)

Example 2
Create a new script (Ctrl + N). Save with the name: Exemple2_TP6.m
for
Create a function that displays the Modify the display function ofn/2
iteration numbers from 0 up to . up to .

Example 3
Create a new script (Ctrl + N). Save with the name: Exemple3_TP6.m
for
We are looking for a function that calculates the Modify the function, We are looking for

sum of1 to n. to calculate the sum of à .


S = 1+ 2 + 3 + 4 + ⋯ + n = +1+2+⋯+b

The instruction: ...


The instruction (as long as) executes one/multiple instructions as long as the condition is
true.

Body of the loop


Logical expression: is an expression whose result
may be true or false;
Sequence of instructions: is the processing to be performed
as long as the logical expression is true.

Note

Course/TP: Computer Science 3 - 35 - Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 06 Control instructions (Loop: for & while)

is generally the result of a test (for example i < Imax) or the


result of a logical function (for example all(x)). It is imperative that the processing of the
é ′ act on the result ’ otherwise we
loop indefinitely.

Example 4
Create a new script (Ctrl + N). Save with the name: Exemple4_TP6.m
Use instruction: while.
Create a Matlab function that Write a Matlab function that
count from 1 to 10. allows to calculate the sum of 1
Use exampleExample1_TP6 up to n.
Use exampleExample3_TP6

Example 5
Create a new script (Ctrl + N). Save it with the name: Exemple5_TP6.m
Use instruction: while.
Create a Matlab function that calculates the product of1jusqu’à .

Create a Matlab function that calculates the factorial of .

Course/TP: Computer Science 3 - 36 - Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 06 Control instructions (Loop: for & while)

Part 02: Simulation Part (Conditions)


Exercise 1 (display elements of any vector)
Create a new script (Ctrl + N). Save with the name: Exercice1_TP6.m
Create a function that displays the elements of a vector one by one on the same
line.
Create a vector of numbers from 1 to n (n<20).
Use instruction:for/while.

Exercise 2 (display elements of matrix)


Create a new script (Ctrl + N). Save with the name: Exercice2_TP6.m
Create a matrixF = [1 2 3; 3 4 5; 6 7 8;
Create a function that displays the elements of a matrix one by one.
Use loops: for or while (you need to use 2 loops).

Course/TP: Computer Science 3 37 Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 06 Control instructions (Loop: for & while)

Exercise 3 (display elements of matrix)


Create a new script (Ctrl + N). Save with the name: Exercice3_TP6.m
Create a function that displays the elements of a random matrix of dimension n
un-park-un.

Exercise 4 (display elements of matrix)


Create a new script (Ctrl + N). Save with the name: Exercice4_TP6.m
Create a function that displays the 3thline of a magic matrix of dimension 5.

Exercise 5 (introduce a matrix element by element)


Create a new script (Ctrl + N). Save with the name: Exercice5_TP6.m
Create a function that introduces element-by-element a square matrix of
dimension n.
Use instruction: for/while.

Course/TP: Computer Science 3 38 Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 06 Control instructions (Loop: for & while)

Part 03: Experimental part (MATLAB–SIMULINK)


Exercise 6 of preparation (matrix inversion test)
Create a new script (Ctrl + N). Save with the name: Exercice6_TP6.m
Create a function that contains a square matrix M of order 12 containing the
integers from 1 to 144 arranged by row.
Calculate the determinant of M.
Calculate the inverse of matrix M.
Extract from this matrix:
A submatrix A formed by the coefficients for: <( , )< ;
A sub-matrix of order 3 formed by the first even coefficients of .
Modify all the diagonal values of the matrix M by the value of zeros.

Course/TP: Computer Science 3 39 Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 07
Graphics (Window management, plot(), fplot())
Lab Sheet: 07 Graphics (Window management, plot(), fplot())

Nour Bachir El-Bayadh University Center


Institute of Sciences
Department of Technology
Spécialité :HYD, GC, ETT, ELN et TLC
Level: Bachelor's 02 (semester 03)
Practical Computer Work 3

TP 07: Graphics (Management of graphic windows, plot(), fplot())

The objective of the TP:

This TP07 aims to introduce you to the management of graphical windows and the tools for
create high-quality scientific graphs that clearly present scientific data.

Part 01: Theoretical Part (Management of 2D Graphics Windows)


While it is useful to be able to perform numerical calculations, it is also useful to have a
graphical representation of the results.
We will start by plotting the graph of a function, the main command that allows
to plot a graph in Matlab is the command () or else ().

The order ()
the instruction () allows to draw
graphically 2D a set of points of
coordinates:
( , ) , = ,…,
Where
is the vector containing the values on the x-axis, and
is the vector containing the values in ordinate.
Of course, the vectors x and y must be of the same dimension, but they can be of
vectors rows or columns. By default, the points (xi,yiare connected to each other by
line segments.

The first thing to do is to look at the function syntax (and understand it)
:
The instruction Plot takes one, two, or three arguments, or multiples of three;
If there is only one argument, plot draws the value of the vector passed as an argument.
according to its index;
If there are two arguments X and Y, plot draws Y as a function of X;
The third argument allows passing options:

Course/TP: Computer Science 3 39 Dr. Ali Abderrazak TADJEDDINE


Sheet TP: 07 Graphics (Management of graphic windows, plot(), fplot())

(Change the color, appearance of the graph, etc.)

Example 1
Create a new script (Ctrl + N). Save with the name: Exemple1_TP7.m
Plot the graph of the function (= ) 5x+ 2between-5 et + 5:

Compare with the instruction ( ) ; to use to display both


functions on the same figure.

Example 2
Createa new script(Ctrl +N). Save with the name :Exemple2_TP7.m
Plot the graph of the function (= ) 5x+ 2between-5 et + 5:

Example 3
Create a new script (Ctrl + N). Save with the name: Example3_TP7.m
Plot the graph of the function (= ) * sin(x)between− :

Use the instruction for a grid in the figure.

Example 4
Create a new script (Ctrl + N). Save with the name: Exemple4_TP7.m
Plot the graph of the functiony1 x =( ) * sin(x)between− :

Course/TP: Computer Science 3 40 Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 07 Graphics (Managing graphic windows, plot(), fplot())

Compare the results of examples 3 and 4, conclude!


In the previous examples, we defined a vector. of evenly distributed values
between− or well− (with a step of 0.001 and 0.01 in the first case and
from 1 in the second case) and we calculated the image by the functionf, g, you y1of these values
(vector of images ), and through the plot instruction, the points with coordinates were displayed.

( ( ), ( )) .

For a curve of any function, we can specify to MATLAB what it should be.
color, what should be the line style and/or what should be the symbol at each point
( , ).

For this, we give a third input parameter to the plot command, which is a string.
of 3 characters in the form′ ′ with designating the color of the line, the symbol of the dot
and the type of stroke. The possibilities are as follows:

Line color symbol of the dot type of line


y yellow . point - full trait
m magenta o circle : short dotted
c cyan x brand x - long dotted
r red + more -. mixed dotted
g green * star
b blue s square
w white d diamond
k black v triangle (base)
^ top triangle
< triangle (left)
> right triangle
p pentagon
h hexagon

The default values are′ = ′, ′ = .′ ′ = − ′ which corresponds to a solid line


blue linking the points together.

It is not mandatory to specify each of the three characters. One can make do with just one of them.
Specify one or two. The others will be the default values. It is possible to trace.
several curves on the same figure by specifying several tables x1, y1, x2, y2, ...
as parameters of the instruction . If one wishes for the curves to have a
different appearance, we will use color options and/or different stroke styles
after each pair of vectors x, y.

Course/TP: Computer Science 3 41 Dr. Ali Abderrazak TADJEDDINE


Work Sheet: 07 Graphics (Window management, plot(), fplot())

Save a figure
The order allows you to save the figure of a graphic window in a
file in various image formats. The syntax of the print command is:
− < >− < >< >
From where:
< > indicates the number of the graphical window (figure 1, 2, ...).
< > refers to the format for saving the figure. These formats are
many. You can get the complete list by typing help plot. For example:
JPEG image format.
< > designates the name of the file in which the figure is saved.

Part 02: Simulation Part (Conditions)


Exercise 1
Create a new script (Ctrl + N). Save with the name: Exercice1_TP7.m
We trace on the intervalx ∈ [-5, 5]the function ( ) = ² ( ) in solid blue line,
et la fonction ( ) = ( ) in red dotted line.

Exercise 2 (the instruction () )


Createa new script(Ctrl +N). Save with the name :Exercice2_TP7.m
If x and y are two vectors of the same dimension, the instruction ( , ) allows
to display the vector ( ) against the vector ( )The order () is used
in the same way as the command ().

What is the slope of the line?

Improving the readability of a figure


Label a figure
To put a caption on a figure:

Course/TP: Computer Science 3 - 42 - Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 07 Graphics (Window management, plot(), fplot())

the order allows adding a text caption under the x-axis.


The syntax is: (′ é ′)
The order do the same for the y-axis: (′ é ′)
The order allows you to give a title to the figure. The syntax is:
′)
( ′
The order allows it to place the text at a chosen position on
the figure using the mouse. The syntax is (′ ′).
Exercise 3 (Improving the caption of a figure)
Create a new script (Ctrl + N). Save with the name: Exercice3_TP7.m
Use the different previous commands to caption a figure.

Exercise 4 (Plot the graph of a function; the command ())


The order allows to plot the graph of a function over a given interval.
Syntax:

(′ ′, [ , ])
Where from:

let it be the name of a built-in MATLAB function (cos, sin ...), soit a
expression defining a function of the variable x, let the name of a function
user.
[ , ] is the interval for which the graph of the function is drawn.

Create a new script (Ctrl + N). Save it with the name: Exercice4_TP7.m
1. Let's illustrate the three ways to use the command. We are looking for the graph of the

sine function− by the instruction: (′ ′, [− ∗ ∗ ]).


2. To plot the graph of the function =( ) (between
) − we can
define the user function in( the
) following way (be careful to properly
read x.*sin(x) and not x*sin(x):
(= )
{
= .∗ ( ) ;
Then look for the graph of the function. ( ) by the instruction: (′ ′, [− ∗ ∗
]).

Course/Practical Work: Computer Science 3 43 Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 07 Graphics (Window management, plot(), fplot())

3. The other way to proceed is to execute the instruction: (′ ∗ ( )′, [− ∗


∗ ]).

Exercise 5 (Plot the graph of a function; the command ())


Create a new script (Ctrl + N). Save with the name: Exercice5_TP7.m
( ) ( )
Let's illustrate two functions ( ) = on [-5;5and ( ) = on [-1; 1]

let's use the instruction [ (′ ] , , [− , , − , ].


Label the figure and use curves with different colors.

Part 03: Experimental part (MATLAB–SIMULINK)


Exercise 6 of preparation ()
Create a new script (Ctrl + N). Save with the name: Exercice7_TP7.m
Plot the graph of the function (= )− − ( −) − on [-10;
using;
The instruction ;
The instruction .
Conclude !!

Exercise 7 preparation (matrix inversion test)


Create a new script (Ctrl + N). Save with the name: Exercice7_TP7.m
Plot the graph of the square function on [-1; 1] using the instruction: ()
Plot the graph of the square function on [-1; 1] using the instruction: ()
Compare the two results.

Exercise 8 of preparation (Superposition of curves in the same figure)


Create a new script (Ctrl + N). Save with the name: Exercice8_TP7.m
Plot the functions ( ) = ( ) on [-1; 1]; g(x) = x on [-1; 1]; h(x) = log(x) on
[1/e; e] on the same figure.
Use the instructions: () ()
Use both instructions:

Course/TP: Computer Science 3 - 44 - Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 08
Use of toolbox
Lab sheet: 08 Utilisation de toolbox

Nour Bachir El-Bayadh University Center


Institute of Sciences
Department of Technology
Spécialité :HYD, GC, ETT, ELN et TLC
Level: Bachelor 02 (semester 03)
Practical Computer Work 3

TP 08: Use of toolbox

The objective of the lab:

This TP08 aims to introduce you to operations on vectors and matrices in order to
use them for solving the exercises.

Part 01: Theoretical Part (Toolbox)


The MATLAB Toolbox is a collection of functions and tools specifically designed for
a specific application. Users can use these functions to perform
specific tasks without having to write their own code. To use a Toolbox, simply
install it and add it to your MATLAB working environment. You can then
access Toolbox functions from the command line or the interface
Graphical user. Some Toolboxes may require a license to be
used, but there are also many free Toolboxes available.

The "toolbox" in MATLAB refers to a set of MATLAB functions.


(also called 'toolboxes') that provide additional features
for a specific application or field of study. These toolkits are distinct from
basic MATLAB system, but can be added to the MATLAB environment as needed.
needs.

For example, there are toolboxes available for control systems, the
image processing, optimization, signal processing, statistics and many
other areas. These toolboxes provide a comprehensive set of functions and tools
to solve problems and perform tasks in the respective field.

Once a toolkit is installed, its functions can be called as


any other MATLAB function, and its user interface tools (such as
dialog boxes or graphical user interfaces can be used to
interact with the toolbox.

Course/TP: Computer Science 3 55 Dr. Ali Abderrazak TADJEDDINE


Practical Sheet: 08 Use of toolbox

Control System Toolbox


Un package pour Matlab composé d'outils spécifiquement développés pour les applications
control. The software package offers data structures to describe
common representations of systems such as state-space models and functions
of transfer, as well as tools for analysis and design of control systems. There are
also system simulation tools.

In this sheet, you will learn about the basic commands of Control System.
Toolbox. When you have completed this exercise, you should be able to
understand and use Control Systems Toolbox to create and analyze systems
linear. Intensive use of the Matlab help command is recommended. It is
Also recommended to create a script file (for example EX01.m) in which you
write your commands.
By executing a script file instead of typing commands directly at the prompt.
In Matlab, it is easier to correct errors and your work will also be saved.
for later use.

Example 1
The system that you will use is:
0 1 0
̇= + =[ ] +[]
-1 -1 1
= = [1 0]

Creation and conversion of systems


The Control System Toolbox supports multiple system representations of systems.
time-invariant linear. In this exercise, we will use two of the
the most common representations; state space models and transfer functions.

Define the matrices of the system A, B, C, and D given above. (What is the value of D)
in the model ?) Create a description of the system's state space using ss and
name it sys_ss. Discover how to use ss by using the help function (help ss). A
At this stage, you should have obtained a description of the system's state space.
Let's now create an equivalent transfer function model of the above system.

This could, as you know, be done using the formula:


( )= ( −) -1 +

Course/TP: Computer Science 3 56 Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 08 Use of toolbox

However, Matlab can also be used for the task. Use the tf command for
convert the state-space model into a transfer function and name it sys_tf. Note
can be used for the creation of transfer functions as well as for conversion.

What is the syntax in both cases respectively?

Example 2 (Stability Analysis)


The stability of a linear system is determined by the location of its poles in the plane.
complex.
What is the stability condition?
Use the ssdata and tfdata commands to extract the necessary data from the models.
Use et roots to determine the stability of the system. Check that the roots of the polynomial
The characteristics of the transfer function are the same as the eigenvalues of the
system matrix.
What are the eigenvalues / poles?
Is the system stable?
You can also use the command pole, or for a graphical view, pzmap.

Exemple 3 (Analyse du domaine temporel)


Use the step command to plot the system's impulse response. Connect them.
characteristics of the index response at the location of the poles. If you have the time,
use initial etlsim to study the system's response.

All the necessary blocks for this model

Course/TP: Computer Science 3 - 57 - Dr. Ali Abderrazak TADJEDDINE


Lab sheet: 08 Use of toolbox

Some useful Matlab commands

Course/TP: Computer Science 3 - 58 - Dr. Ali Abderrazak TADJEDDINE


Lab sheet: 08 Use of toolbox

Introduction to Simulink
The Simulink instruction provides a simulation program based on Matlab named
Simulink. There are several ways to define a model. One can work graphically.
and connect flowcharts with predefined blocks. Alternatively, one can
provide the mathematical description in the form of differential equations in a file
m (the format of programs written in the Matlab programming language).
Matlab/Simulink supports both representations as well as combinations of them.
Moreover, we can use descriptions that include a hierarchy of subsystems.
connected.

To understand how models are described and simulated using diagrams.


functional, it is better to run small examples on a computer. The rest of the
Section 2 shows some examples. If you know Simulink, you can skip.
directly to section 3.

How to start Simulink


Enter the simulink command in Matlab (command window). This opens a window.
with blocks like in the figure below.

Course/TP: Computer Science 3 59 Dr. Ali Abderrazak TADJEDDINE


TP sheet: 08 Use of toolbox

A simple system
Click on File in the Simulink window and choose New->Model.
Click on the Continuous block and move a Transfer Fcn to the new window
called 'untitled'.
Do the same with Source->Step Fcn and Sinks->Scope.
Draw arrows (left mouse button) and connect the ports on the block.
You should now have a functional diagram as shown in the following figure.

Choose Simulation->Settings in the window titled "untitled".


Set the stop time to 5. Open the Range window by double-clicking on it.
Set the horizontal bar to 6.
Start a simulation by Simulation->Start (or by pressing Ctrl-t in the
window titled "Untitled".

Example 4 (changing a system)


To change the system to:
7
2+ 0.5s +2

Double click on Transfer Fcn

Course/TP: Computer Science 3 - 60 - Dr. Ali Abderrazak TADJEDDINE


Sheet TP: 08 Use of toolbox

You should now have a functional diagram like in the figure below.

The system becomes:

How to change an input signal To change the input signal, start by


supprimer le bloc Step Fcn en cliquant dessus et supprimez-le en utilisant Edit->Cut (ou en
pressing Ctrl-x). Replace it with a block Sources->Signal Gen. Double-click on
Signal Gen and select the signal, amplitude, and frequency. Also modify
Simulation->Start->Stop time at 99999 and press Simulation->Start.
This creates an 'infinite' simulation that can be stopped by pressing Simulation -> Stop
(or Ctrl-t).
Can the amplitude of the input signal be modified during the simulation? Try.
also to change the Transfer Fcn block during the simulation.
How to use Matlab variables in the blocks Note that the variables defined in
The Matlab environment can be used in Simulink. Define the numerator and the
denominator by writing the following in the Matlab window.

Course/TP: Computer Science 3 - 61 - Dr. Ali Abderrazak TADJEDDINE


Practice Sheet: 08 Use of toolbox

nombre=[7 6]
repaire=[1 2 3 4]
Replace Transfer Fcn->Numerator with num and Transfer Fcn->Denominator with den.

How to save the results in Matlab variables To save the input and the
Output, move two copies of the block Sinks->To Workspace. Make sure that the option
"Save the format" is set to "Array", see figure 2. Connect them with the input and the
output at the Transfer Fcn block. Also obtain a Source-> Clock and connect it to a
Sinks-> To Workspace. Replace the variable names with u, y, t respectively. The window
it should look like the figure.

Course/TP: Computer Science 3 - 62 - Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 08 Use of toolbox

How to use the simulation results in Matlab calculations Suppose that


the input signal is sinusoidal with a frequency of 0.1 rad/s and an amplitude of
Perform a simulation long enough for the output to become
stationary.
Calculate the maximum value of y when the system has stabilized.
n=length(y)
max(y(n/2:n))

Use of Simulink models in Matlab scripts


Often, it is convenient to work with Matlab scripts (m files) in order to save
a sequence of commands. It is possible to use Simulink models from a script
Matlab, using the command sim. Using the command simset, the options of the
SIM commands can be specified.

Use the model from the previous example. Save the model and name it.
"mymodel.mdl". Create a Matlab script named "mysim.m", and enter the commands
following:

1.tfinal = 300;
2.options= simset('reltol',1e-5,'refine',10,'solver','ode45');

3.sim('mymodel', tfinal, options);

%plot results
4.figure(1)
5.clf
6.subplot(211)
7.plot(t,u);
8.ylabel('u')
9.subplot(212)
10.plot(t,y)
11.ylabel('y')

When you run the script, you should see a plot showing the input and output of
the transfer function. Use the help command to learn more about the usage of the
simset and sim commands.
How to save systems Use File-Save As or File-
Save.

Course/TP: Computer Science 3 63 Dr. Ali Abderrazak TADJEDDINE


TP Sheet: 08 Use of toolbox

Part 02: Simulation Part (A flow system)


Consider a simple tank as in the basic control course
1
ℎ̇ = ( − )

= √2 ℎ
This can be implemented in Simulink as shown in the figure below. The function f(u) has
the value ∗ (2∗ )∗ ( [1])The Sum block received two inputs with signs
different by assigning the string "-+|" to Sum->List of signs. The input blocks and
outlets are respectively located under the sources and the wells.

These blocks indicate to Simulink what should be considered as inputs and outputs.
towards this subsystem. The block titles can be changed by clicking on them. Mark
the whole system by holding down the left mouse button and drawing
a square around. Then, choose Edit -> Create a subsystem. The result is that the
the system is represented by a block. Use Edit->Copy to create the double system
next tank.

Exercise 1
Use the command linmod to find a linearized model of the double reservoir around
ofℎ10= ℎ20= 0.1Use the parameters 1= 2 = 2.7 10−3 , 1 = 2 = 7× 10−6 , =
9.8. Also note in the figure the Simulink block from the sources and the block
Simulink from the wells, which are necessary for the linmod command.

>> A=2.7e-3; a=7e-6; g=9.8;

x0 = [0.1000 0.1000]';
u0 = a*sqrt(q*g*x0(1));
>> [aa, bb, cc, dd] = linmod('flow', x0, u0);

Course/TP: Computer Science 3 64 Dr. Ali Abderrazak TADJEDDINE


Lab sheet: 08 Use of toolbox

Part 03: Experimental part (MATLAB–SIMULINK)


Exercise 6
Build a Simulink model to calculate the values of the cosine function g(t) = cos
(ωt) for t = 0…3 with 3,000 incremental steps and ω= [π, 2π, 3π, 5π, 7π] specified in
MATLAB. Simulate your Simulink model using MATLAB with the sim() command.
using a loop [for ... end] or [while ... end] for all values of ω.

Exercise 7
The acceleration of a skydiver is determined by:
2
a = g(1 - )
3600

Where: g = 9.81 m/sec².


Create a Simulink model to simulate the acceleration of a skydiver.

Exercise 8
The introduction of transfer functions is done in several polynomial forms,
ZPK form (zeros, poles, gain), state space form. Let's take some types of controlled systems.
second and third order to train on the declaration of these systems.
s+5 s + 10
1( ) = 3+ 8s2+ 17s + 10
; 2 ( ) =
2 2+ 3s + 1
( − 2)(s + 1.2)
3 ( ) = 4.25
(s + 0.3)(s + 1)(s + 5)
1. Consult the online help on the Tf, ZPK, TF2SS, TF2ZP commands
2. Create a command file tp3ex1.m for the MATLAB commands of the exercise
No. 1
3. Introduce ( ) and ( under MATLAB
4. Give the poles of these two systems.

5. Introduce the system ( using the ZPK command

6. Transition from the transfer function representation of ( ) and ( to the ZPK form
known by Evans' shape ( ) = ( - ( ))( - ( ))...( - ( )) ( - ( ))( -
( ))...( - ( ))).
7. Move from the transfer function representation of f₁(s) and f₂(s) to the state-space form

=
C
X
y+
D
=
A
u
.X
+
B
u
,X
̇
8. Change from the ZPK representation of f(s) to the form Ẋ = AX + Bu, y = CX + Du.

9. Save the workspace of this exercise in tp3ex1.mat

Course/Practical Work: Computer Science 3 65 Dr. Ali Abderrazak TADJEDDINE


Lab Sheet: 08 Use of toolbox

Exercise 9 (Construction of Functional Diagrams)


Let the functional diagram given by the figure below

1. Consult the online help on Series, Parallel, feedback orders


2. Create a command file tp3ex2.m for the MATLAB commands of
exercise No. 2
3. Give the open-loop transfer function.
4. Give the closed-loop transfer function (Y(s)/U(s))
5. Check the result analytically.
6. Calculate the poles of the closed-loop transfer function
7. Convert this transfer function to the different forms (ZPK, SS) of the system.
in BF
8. Save the workspace of this exercise in tp3ex2.mat

Course/Practical: Computer Science 3 66 Dr. Ali Abderrazak TADJEDDINE


Bibliographic References
Bibliographic References
Course / Lab: Computer Science 3

According to the availability of documentation at the institutional level, websites, etc.


1. SCILAB :
1.1.Informatique: Programmation et simulation en Scilab 2014- Auteurs : Arnaud
Bégyn, Jean-Pierre
Attic, Hervé Gras.
1.2.Scilab: From Theory to Practice - I. The Basics. Book by Philippe Roux
2013.

2. MATLAB :
2.1.French References:
Introduction to MATLAB and SIMULINK, A guide for students of the National School
Superior School of Electric Engineers of Grenoble, Paolino Tona.
C++ for Dummies, Stephen Randy Davis.

2.2. Arabic References:


‫ﺩﺳﻴﻦﻥﻟﻤﻪﻝﻣﺎﺕﻻﺏﺍﻝ‬، ‫ﻥﺷﺎﻫﻲﻥﺍﻥﻋﺪﺩﺱﻥ ﻩﻟﻢﺍ‬

2.3. Références Anglaises:


- Essential MATLAB for Engineers and Scientists, Seventh Edition, Brian D. Hahn
& Daniel T. Valentine.
- Numerical Analysis Using MATLAB and Excel, Steven T. Karris.
- Matlab for Dummies, Jim Sizemore, John Paul Mueller.

Course: Fundamental Electrotechnics 1 68 Dr. Ali Abderrazak TADJEDDINE


End
Course / Lab: Computer Science 3

You might also like