TP Informatique: Raport N 01 Introduction To MATLAB

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

Universite abbes laghrour de khenchela faculte des

sciences et de la technologie

TP Informatique
« Génie des matériaux »

Raport n 01
« Introduction to MATLAB »

Etudiant: wafik farsi Enseignement : fougali yousef

Année universitaire :2021.2022


1.2 Basic features :
The lessons are intended to make you familiar with the basics of
MATLAB.
1.3 A minimum MATLAB session :
The goal of this minimum session (also called starting and exiting sessions) is to learn the
flrst steps:
† How to log on
† Invoke MATLAB
† Do a few simple calculations
† How to quit MATLAB
1.3.1 Starting MATLAB
After logging into your account, you can enter MATLAB by double-clicking on the MATLAB
shortcut icon (MATLAB 7.0.4) on your Windows desktop. When you start MATLAB, a
special window called the MATLAB desktop appears. The desktop is a window that contains
other windows. The major tools within or accessible from the desktop are:
† The Command Window
† The Command History
† The Workspace
† The Current Directory
† The Help Browser
† The Start button
1.3.2 Using MATLAB as a calculator
For example, let’s suppose you want to calculate
the expression, 1 + 2 × 3. You type it at the prompt command (>>) as follows,
>> 1+2*3
ans =
7
You will have noticed that if you do not specify an output variable, MATLAB uses a
default variable ans, short for answer, to store the results of the current calculation. For
example,
>> x = 1+2*3
x=
7
1.3.3 Quitting MATLAB :
To end your MATLAB session, type quit in the Command Window, or select File −→ Exit
MATLAB in the desktop main menu.
1.4 Getting started :
After learning the minimum MATLAB session, we will now learn to use some additional
operations.
1.4.1 Creating MATLAB variables :

The syntax of variable assignment is

variable name = a value (or an expression)

1.4.2 Overwriting variable :


Once a variable has been created, it can be reassigned. and you can suppress the numerical
output by putting a semicolon

(;) at the end of the line. Then the sequence of commands looks like this:

>> t = 5;

>> t = t+1

t=

1.4.3 Error messages

If we enter an expression incorrectly, MATLAB will return an error message.

Error: Unexpected MATLAB expression.

1.4.4 Making corrections :


To make corrections, we can, of course retype the expressions.. A previously typed
command

can be recalled with the up-arrow key ↑, it can be modified if needed and executed.

1.4.5 Controlling the hierarchy of operations or precedence :


Let’s consider the previous arithmetic operation, but now we will include parentheses. For

example, 1 + 2 × 3 will become (1 + 2) × 3


>> (1+2)*3

ans =

The order in which MATLAB performs arithmetic operations is exactly that taught

in high school algebra courses. Exponentiations are done first, followed by multiplications

and divisions, and finally by additions and subtractions. However, the standard order of

precedence of arithmetic operations can be changed by inserting parentheses

in Table 1.2. MATLAB arithmetic operators obey the same precedence rules as those in

Table 1.2: Hierarchy of arithmetic operations

Precedence Mathematical operations

First The contents of all parentheses are evaluated first, starting

from the innermost parentheses and working outward.

Second All exponentials are evaluated, working from left to right

Third All multiplications and divisions are evaluated, working

from left to right

Fourth All additions and subtractions are evaluated, starting

from left to right

1.4.6 Controlling the appearance of floating point number :


MATLAB by default displays only 4 decimals in the result of the calculations However,
MATLAB does numerical calculations
in double precision, which is 15 digits. Here are some examples of the different formats
together with
the resulting outputs.
>> format short
>> x=-163.6667
If we want to see all 15 digits, we use the command format long
>> format long
>> x= -1.636666666666667e+002
Note : To prevent MATLAB from echoing what we type, simply enter a semicolon (;) at
the end of the command. For example,
>> x=-163.6667;
and then ask about the value of x by typing,
>> x
x=
-163
1.4.7 Managing the workspace :
To avoid problems, you must to issue a clear command at the start of each new
independent calculation.
>> clear
The command clear or clear all removes all variables from the workspace. This
frees up system memory. In order to display a list of the variables currently in the memory,
type
>> who
while, whos will give more details which include size, space allocation, and class of the
variables.

1.4.8 Keeping track of your work session :


It is possible to keep track of everything done during a MATLAB session with the diary
command.
>> diary
or give a name to a created file,
>> diary FileName
where FileName could be any arbitrary name you choose.
1.4.9 Entering multiple statements per line :
It is possible to enter multiple statements per line. Use commas (,) or semicolons (;) to
enter more than one statement at once. Commas (,) allow multiple statements per line
without suppressing output.
>> a=7; b=cos(a), c=cosh(a)
b=
0.6570
c=
548.3170
1.4.10 Miscellaneous commands :
Here are few additional useful commands:
• To clear the Command Window, type clc
• To abort a MATLAB computation, type ctrl-c
• To continue a line, type . . .
1.4.11 Getting help :
To view the online documentation, select MATLAB Help from Help menu or MATLAB Help
directly in the Command Window.
Another way to get help is to use the lookfor command. The lookfor command differs
from the help command. The help command searches for an exact function name match,
while the lookfor command searches the quick summary information in each function for
a match.
Chapter 2
Tutorial lessons 2 2.1 :
Mathematical functions :
MATLAB offers many predefined mathematical functions for technical computing which
contains a large set of mathematical functions. Typing help elfun and help specfun calls up
full lists of elementary and special functions respectively. There is a long list of mathematical
functions that are built into MATLAB. These functions are called built-ins. Many standard
mathematical functions, such as sin(x), cos(x), tan(x), e x , ln(x), are evaluated by the
functions sin, cos, tan, exp, and log respectively in MATLAB. Table 2.1 lists some commonly
used functions, where variables x and y can be numbers, vectors, or matrices.

Table 2.1: Elementary functions

In addition to the elementary functions, MATLAB includes a number of predefined

constant values. A list of the most common values is given in Table 2.2.

Table 2.2: Predefined constant values :


2.2 Basic plotting :
2.2.1 overview :
MATLAB has an excellent set of graphic tools. Plotting a given data set or the results
of computation is possible with very few commands. You are highly encouraged to plot
mathematical functions and results of analysis as often as possible.
2.2 Basic plotting :
2.2.1 overview :
MATLAB has an excellent set of graphic tools. Plotting a given data set or the results
of computation is possible with very few commands.
2.2.3 Multiple data sets in one plot :
Multiple (x, y) pairs arguments create multiple graphs with a single call to plot. For example,
these statements plot three related functions of x: y1 = 2 cos(x), y2 = cos(x), and y3 =
0.5 ∗ cos(x), in the interval 0 ≤ x ≤ 2π.
>> x = 0:pi/100:2*pi;
>> y1 = 2*cos(x);
>> y2 = cos(x);
>> y3 = 0.5*cos(x);
2.2.5 Specifying line styles and colors :
It is possible to specify line styles, colors, and markers (e.g., circles, plus signs, . . . ) using
the plot command:
plot(x,y,’style_color_marker’)

2.4 Introduction :
Matrices are the basic elements of the MATLAB environment. A matrix is a two-dimensional
array consisting of m rows and n columns. Special cases are column vectors (n = 1) and row
vectors (m = 1).
In this section we will illustrate how to apply different operations on matrices
2.5 Matrix generation :
we need to become familiar with matrix
generation and manipulation. Matrices can be generated in several ways .
2.5.1 Entering a vector :
A vector is a special case of a matrix. The purpose of this section is to show how to create
vectors and matrices in MATLAB. As discussed earlier, an array of dimension 1 ×n is called
a row vector, whereas an array of dimension m × 1 is called a column vector. The elements
of vectors in MATLAB are enclosed by square brackets and are separated by spaces or by
commas. For example, to enter a row vector, v, type
>> v = [1 4 7 10 13]
v=
1 4 7 10 13
Column vectors are created in a similar way, however, semicolon (;) must separate the
components of a column vector,
>> w = [1;4;7;10;13]
w=
1
4
7
10
13
On the other hand, a row vector is converted to a column vector using the transpose
operator.
The transpose operation is denoted by an apostrophe or a single quote (’).
>> w = v’
w=
1
4
7
10
13

Thus, v(1) is the first element of vector v, v(2) its second element,
Furthermore, to access blocks of elements, we use MATLAB’s colon notation (:). For
example, to access the first three elements of v, we write,
>> v(1:3)
ans =
147
Or, all elements from the third through the last elements,
>> v(3,end)
ans =
7 10 13
where end signifies the last element in the vector. If v is a vector, writing
>> v(:)
produces a column vector, whereas writing
>> v(1:end)
produces a row vector.
2.5.2 Entering a matrix :
A matrix is an array of numbers. To type a matrix into MATLAB you must
• begin with a square bracket, [
• separate elements in a row with spaces or commas (,)
• use a semicolon (;) to separate rows
• end the matrix with another square bracket, ].
2.5.3 Matrix indexing :
We select elements in a matrix just as we did for vectors, but now we need two indices.
The element of row i and column j of the matrix A is denoted by A(i,j). Thus, A(i,j)
in MATLAB refers to the element Aij of matrix A. The first index is the row number and
the second index is the column number. For example, A(1,3) is an element of first row and
third column. Here, A(1,3)=3.
Correcting any entry is easy through indexing. Here we substitute A(3,3)=9 by
A(3,3)=0. The result is
>> A(3,3) = 0
A=
123
456
780
2.5.4 Colon operator :
It occurs in several different forms.
Often we must deal with matrices or vectors that are too large to enter one element at a
time. For example, suppose we want to enter a vector x consisting of points
(0, 0.1, 0.2, 0.3, · · · , 5). We can use the command
>> x = 0:0.1:5;
2.5.5 Linear spacing :
On the other hand, there is a command to generate linearly spaced vectors: linspace. It
is similar to the colon operator (:), but gives direct control over the number of points. For
generates a row vector y of 100 points linearly spaced between and including a and b.
y = linspace(a,b,n)
generates a row vector y of n points linearly spaced between and including a and b. This is
useful when we want to divide an interval into a number of subintervals of the same length.
For example,
>> theta = linspace(0,2*pi,101)
divides the interval [0, 2π] into 100 equal subintervals, then creating a vector of 101
elements.
2.5.6 Colon operator in a matrix :
The colon operator can also be used to pick out a certain row or column. For example, the
statement A(m:n,k:l specifies rows m to n and column k to l. Subscript expressions refer
to portions of a matrix
2.5.7 Creating a sub-matrix
To extract a submatrix B consisting of rows 2 and 3 and columns 1 and 2 of the matrix A,
do the following
>> B = A([2 3],[1 2])
B=
45
78
To interchange rows 1 and 2 of A, use the vector of row indices together with the colon
operator.
>> C = A([2 1 3],:)
C=
456
123
780
It is important to note that the colon operator (:) stands for all columns or all rows. To
create a vector version of matrix A, do the following
>> A(:)
ans =
1
2
3
4
5
6
7
8
0
The submatrix comprising the intersection of rows p to q and columns r to s is denoted by
A(p:q,r:s).
As a special case, a colon (:) as the row or column specifier covers all entries in that row or
column; thus
• A(:,j) is the jth column of A, while
• A(i,:) is the ith row, and
• A(end,:) picks out the last row of A.
2.5.8 Deleting row or column :
To delete a row or column of a matrix, use the empty vector operator, [ ].
>> A(3,:) = []
A=
123
456
Third row of matrix A is now deleted. To restore the third row, we use a technique for
creating a matrix
>> A = [A(1,:);A(2,:);[7 8 0]]

A=
123
456
780
Matrix A is now restored to its original form
2.5.9 Dimension :
To determine the dimensions of a matrix or vector, use the command size. For example,
>> size(A)
ans =
33
means 3 rows and 3 columns.
Or more explicitly with,
>> [m,n]=size(A)
2.5.11 Transposing a matrix :
The transpose operation is denoted by an apostrophe or a single quote (’). It flips a matrix
about its main diagonal and it turns a row vector into a column vector. Thus,
>> A’
ans =
147
258
360

2.5.12 Concatenating matrices :


Matrices can be made up of sub-matrices. Here is an example. First, let’s recall our previous
matrix A.
A=
123
456
789
The new matrix B will be,
>> B = [A 10*A; -A [1 0 0; 0 1 0; 0 0 1]]
B=
1 2 3 10 20 30
4 5 6 40 50 60
7 8 9 70 80 90
-1 -2 -3 1 0 0
-4 -5 -6 0 1 0
-7 -8 -9 0 0 1

Chapter 3 :
Array operations and Linear
Equations :
3.1 Array operations :
MATLAB has two different types of arithmetic operations: matrix arithmetic operations
and array arithmetic operations. We have seen matrix arithmetic operations in the previous
lab. Now, we are interested in array operations.
3.1.1 Matrix arithmetic operations :
As we mentioned earlier, MATLAB allows arithmetic operations: +, −, ∗, and ˆ to be
carried out on matrices. Thus,
A+B or B+A is valid if A and B are of the same size
A*B is valid if A’s number of column equals B’s number of rows
A^2 is valid if A is square and equals A*A
α*A or A*α multiplies each element of A by α
3.1.2 Array arithmetic operations :
since the matrix and array operations are the same for addition
(+) and subtraction (−), the character pairs (.+) and (.−) are not used. The list of array
operators is shown below in Table 3.2. If A and B are two matrices of the same size with
elements A = [aij ] and B = [bij ], then the command
>> C = A.*B
produces another matrix C of the same size with elements cij = aij bij . For example, using
the same 3 × 3 matrices,

we have,
>> C = A.*B

C=
10 40 90
160 250 360
490 640 810
to produce a new matrix whose elements are the square of the elements of the matrix A,
we
enter
>> A.^2
ans =
149
16 25 36
49 64 81
The relations below summarize the above operations. To simplify, let’s consider two
vectors U and V with elements U = [ui] and V = [vj].
3.2 Solving linear equations :
With matrix notation, a system of simultaneous
linear equations is written
Ax = b (3.1)
In linear algebra we learn that the solution to Ax = b can be written as x = A−1
b, where
A−1
is the inverse of A.
For example, consider the following system of linear equations

The coefficient matrix A is

There are typically two ways to solve for x in MATLAB:


1. The first one is to use the matrix inverse, inv.
>> A = [1 2 3; 4 5 6; 7 8 0];
>> b = [1; 1; 1];
>> x = inv(A)*b
x=
-1.0000
1.0000
-0.0000
2. The second one is to use the backslash (\)operator. The numerical algorithm behind
this operator is computationally efficient. This is a numerically reliable way of solving
system of linear equations by using a well-known process of Gaussian elimination.
>> A = [1 2 3; 4 5 6; 7 8 0];
>> b = [1; 1; 1];
>> x = A\b
x=
-1.0000
1.0000
-0.0000
3.2.1 Matrix inverse :
Let’s consider the same matrix A.

Calculating the inverse of A manually is probably not a pleasant work. Here the
handcalculation of A−1 gives as a final result:

In MATLAB, however, it becomes as simple as the following commands:


>> A = [1 2 3; 4 5 6; 7 8 0];
>> inv(A)
ans =
-1.7778 0.8889 -0.1111
1.5556 -0.7778 0.2222
-0.1111 0.2222 -0.1111
which is similar to:

and the determinant of A is


>> det(A)
ans =
27
For further details on applied numerical linear algebra, see [10] and [11].

3.2.2 Matrix functions :


MATLAB provides many matrix functions for various matrix/vector manipulations

You might also like