0% found this document useful (0 votes)
12 views5 pages

PW Matrices and Vectors: The Index 0 (N, M) NXM N M (I) (J)

The document provides an introduction to matrices and vectors in Python, emphasizing the use of the NumPy library for efficient manipulation of these data structures. It covers matrix creation, element access, operations, and predefined functions, along with practical exercises for applying these concepts. Additionally, it includes a reminder on Python lists and basic operations associated with them.

Uploaded by

limanidiaadayo
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)
12 views5 pages

PW Matrices and Vectors: The Index 0 (N, M) NXM N M (I) (J)

The document provides an introduction to matrices and vectors in Python, emphasizing the use of the NumPy library for efficient manipulation of these data structures. It covers matrix creation, element access, operations, and predefined functions, along with practical exercises for applying these concepts. Additionally, it includes a reminder on Python lists and basic operations associated with them.

Uploaded by

limanidiaadayo
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/ 5

Setif University -1- Computer Science

Faculty of Technology III 2nd year TC-ST


Department E.B.T A.U: 2024/2025

PW Matrices and vectors


1. Introduction :
In algorithmics, an array (vector) is a type of data that allows grouping a finite number of
elements, all of which are of the same type (real, integer, Boolean,etc.). The elements are identified
by their position (called the index) within the array (typically starting with 0 for the first element).
A size matrix (N, M) is a two-dimensional array containing N x M values of the same type, represented
as N rows and M columns. Each element of the matrix is identified by two indices: the row number (i)
and the column number (j).
In Python, to present a table, we use the List type (covered in
the first year; see reminder at the end of the series). However, for
large numerical tables, we will use the array type from the
Numpy library which allows for better manipulation.
2. The Numpy Library :
NumPy is the fundamental package for manipulating
matrices in Python. It is a Python library that allows creating multidimensional arrays (matrices),
accompanied by a large number of functions and operations that are easy and fast for manipulation
of matrices. NumPy includes mathematical, logical, shape, sorting, selection, Input/Output, linear
algebra, statistical operations.
In Numpy, an array is an ordered sequence of n elements of the same type (floating, integer or
even boolean encoded in binary) indexed from 0 to n-1 (the first element is marked by 0 (zero)).
3. Creating a matrix :
To create a matrix:
- The numpy module must be imported beforehand.
- We use the array function and the brackets "[" and "]" to delimit a matrix.
- Elements in the same row are separated by commas "," and also delimited by "[" and "]".
- Rows are separated by ",".
 Application 1 : Create a matrix (or vector) by typing
>>> import numpy as np # Creating a Row Vector
# total number of values
>>> A = np.array([[1, 2, 3],[4, 5, >>> V = np.array([[1, 2, 3]]),
>>> A.size # np.size(A)
6],[7, 8, 9]]) >>> V.shape
# Implicit Creation and Typing
# Matrix Display # Creating a Column Vector
>>> b = np.array([[1,2],[4,7]])
>>> A V = np.array([[1], [2], [3]])
>>> b.dtype
>>> V.shape
# Structure Type
# Explicit creation and typing
>>> type(A) # using sequences
# (preferable!)
>>> V = np.arange(1, 10)
# Data Type >>> b =np. array([[1,2],[4,7]], float)
>>> A.dtype >>> b.dtype # Reshape
>>> C = V.reshape(3, 3)
# number of dimensions # transposed matrix
>>> A.ndim # np.ndim(A) >>> A.T # np.transpose(A) # using linspace
>>> V =np.linspace(1, 10, 5)
# Number of rows and columns
# linspace(start, end, nbr_valeurs)
>>> A.shape # np.shape(A)

PW N°03 : Matrices and vectors Page - 1 -


Note :
- To display the values of a matrix (or vector) in a script, simply write:
print (Matrix_name)
- To read the values of a matrix (or a vector) one by one with a keyboard, loops must be used.
4. Manipulating the elements of a matrix:
Given a matrix of values denoted A:
- To select an element of the matrix in the ith row and the jth column, we write
A[i-1, j-1].
- To select the ith row or the jth column, use A[i-1, :] or A[ :, j-1]
respectively.
- To select a group of elements, use A[i1 : i2+1, j1:j2+1], where i1, i2 and j1 ,j2 are the bounds
of rows and columns respectively.
Note: We can replace the subscript i or j with -1 to get the last element.
# Creating a Vector
>>> V = np.array([2, 4, 6, 8, 10, 12, 20]) # Matrix Change
>>> A[1,2] = 0 , A[-1, -1] = -4
# Acces to vector elements.
>>> A[2,:] = np.arange(1, 5)
>>> V[0], V[2] , V[-1] , V[-2]
>>> A[1:, 2:] = 0
# Creating a matrix
# add a row – works for concatenation
>>> A = np.array([[1, 4, 5, 12],[-5, 8,
9, 0],[-6, 7, 11, 19]]) # form 1 of matrices
>>> Vl = np.array([[1, 2, 3, 4]])
# Access to matrix elements. >>> C = np.append(A, Vl, 0)
>>> A[0][0], A[0, 0]
#add a column
>>> A[1, 2], A[-1, -1] >>> Vc = np.array([[1], [2], [3]])
# Access to matrix rows. >>> D = np.append(A, Vc, 1))

>>> A[0 ,:], A[1 , :], A[-1, :] #insertion


>>> np.insert(A, 2, Vl, 0)
# Access to matrix columns. >>>np. insert(A, [2], Vc, 1)
>>> A[:, 0], A[:, 1], A[:, -1]
# Access to vector or matrix parts. #deletion
>>> V[2: 5], V[:5], V[5:] >>> np.delete(A, 1, 0)
>>> V[:] >>> np.delete(A, 1, 1)
>>> A[:1, :], A[1:, 2:]
>>> A[:, 1:3]
5. Matrix operations: There are three types of operations in matrix calculation:
Term by term transactions Addition (+) applied to two matrices of the
Subtraction (-) same size.
Multiplication (*)
Division (/)
Power (**)
Operations between matrices Product (dot()) for which the size of the matrices
Inverse of Matrix (linalg.inv()) must be compatible.

PW N°03 : Matrices and Vectors Page - 2 -


Operations between a Addition (+) where there is no restriction.
number and a matrix Subtraction (-)
Multiplication (*) and division (/)
Power (**)
Table 1: Matrix transactions
Remarks:
- Writing 1 / A performs element-wise division, while the linalg.inv(A) function performs
matrix inversion (equivalent to 1/A mathematics).
Application.3 : apply arithmetic operations on matrices.
>>> A = np.arange(1, 10) >>>A+2 , A-2 , A*2, A /2. >>> C = np.diag(A)
>>>np. dot(A, B) # A.dot(B)
>>> A.reshape(3, 3) >>> A ** 2, A // 2, A % 2. >>> A = np.random.randint(100, size=(3, 3))
>>> np.linalg.det(A) # |A|
>>> B = 2 * np.ones((3,3)) >>> A+ B , A * B , A / B , A ** B >>> np.linalg.inv(A) # A-1

6. Functions on matrices:
There are many predefined functions in Python's numpy package that are applied to matrices,
either to create matrix-types, or for common operations to be applied to the entire matrix, or to its
rows or columns separately.
Application.4 : Explore the predefined matrices and some common calculations.
>>> A = np.eye(4, 4) >>> np.concatenate((A, B), 0) >>> F = np.diag(E)
>>> B = np.ones((4,1)) >>>np. concatenate((A, B), 1)
>>> C = np.zeros((4, 4)) >>> E = np.diag(D)
>>> D = np.random.randint(100, size=(3, 3))

Application.5: Make some statistics about the matrix A defined in the application.4.
>>> A = np.arange(1, 10).reshape(3, 3) >>> A.max(),A.min() >>> np.sort(A) # A.sort()
>>> np.sum(A),np. sum(A, 0) >>> A.max(0) >>> np.sort(A, 0)
>>> np. sum(A, 1) >>> A.min(1) >>> A[A % 2 == 0]
>>> np.prod(A), np.prod(A, 0) >>> A[:1, :].max() >>> A[(A>4) & (A<7)]
>>> np.mean(A), np.mean(A, 1) >>> A[1:, 1:].min() >>> where(A > 8) & (A < 45) )

7. Training :
Exercise.1: Solving a linear system
We consider the system of 3 equations:

9𝑥𝑥 + 10𝑦𝑦 + 5𝑧𝑧 = 40


�10𝑥𝑥 + 9𝑦𝑦 + 𝑧𝑧 = −50
𝑥𝑥 + 5𝑦𝑦 + 9𝑧𝑧 = 180

Write a Python script that allows to:


1. Create and display the matrix A of the coefficients.
2. Create and display the Vector B of the Results.
3. Derive the vector X of roots x, y, z by solving the linear system A × X = B.

PW N°03 : Matrices and Vectors Page - 3 -


Exercise.2: Manipulating the matrices
Write a Python script that allows to:
• Define the matrix  Extracted sub-matrix from the matrix
1 5 9 13 17 6 18 10
2 6 10 14 18 7 19 11
3 7 11 15 19 8 20 12
4 8 12 16 20

Exercise.3 : Matrix Traversal Using Indices


- Write a Python script that creates an M(n , m) matrix of random integer values (M i, j <= 100) , such
that m and n are two integers read from keyboard (m>2 , n>2)
- Use a loop (first a for loop then a while loop) to traverse the elements of the matrix M(m, n)
and calculate the sum of the elements of M.
Exercise.4: Pascal's triangle
Write a Python script to construct a square matrix P(n+1, n+1) and display the PASCAL’s triangle of
degree n.
N.B : The elements of PASCAL’s triangle are calculated as follows:
Pi,0 = Pi,i = 1 ∀0≤i≤n
P i,j = P i-1,j-1 + P i-1,j ∀ 1 < i ≤ n and 1 ≤ j < i
Example : Pascal's triangle of degree 5:
N=0 - 1
N=1 - 1 1
N=2 - 1 2 1
N=3 - 1 3 3 1
N=4 - 1 4 6 4 1
N=5 - 1 5 10 10 15 1

M
C
1 2 … 10
Exercise.5: Matrices & functions
11 12 … 20 1 10
a) Define the following functions: 91 100
1. MCoins(M) : flips the four corners of matrix M into a
matrix C of size (2,2). 91 92 … 100

2. MReplace(M,v1,v2) : replaces the V1 value in the M matrix with the V2 value.

0 4 5 0 0 5
0 5 19
4 5 19
V1=4, V2=0 7 2 0
7 2 4

- Modify the MReplace(M,v1,v2) function, so that it also returns the number of replacements n.
b)
- Create a matrix A (4x4) of positive integer random values <10.
- Construct the matrix B(2x2) which contains the four corners of A.
- Replace a value in the matrix A with a zero (0).

PW N°03 : Matrices and Vectors Page - 4 -


8. Reminder on Python Lists :
A list is an aggregate of elements written within square brackets " [.] " and separated by commas “,”.
These elements are identified by their position (or index).
Python allows the construction of lists containing values of different types (integer,string,etc.)
which gives them great flexibility.

8.1 Some basic operations on the lists:


The order Explanation Example
>>> L = []
[] # empty list
>>> type(L), <class 'list'>
L=[ 'b', 'c', 'd', 'd'] # create a list L >>> L=[ 'b', 'c', 'd', 'd']
>>> L.append('e')
list.append(item) # add an element at the end
L=* 'b', 'c', 'd', 'd','e'+
>>>'a' in L
item in list # tests membership in the list
False
>>> L.insert(0, 'a')
list.insert(position, element) # Add an element at a specific position
>>> L, ['a', 'b', 'c', 'd', 'd', 'e']
>>> len(L)
Len(list) # Number of items
6
>>>L[2]
list[position] # access an element by position
'c'
>>> L[2:4]
list[top:end] # access a sublist
['c', 'd']
>>> L[3] = 'D'
del liste[position] # delete an element by position
>>> L, ['a', 'b', 'c', 'D', 'e']
>>> L[3] = 'D'
list[position] = element # modify an item
>>> L , ['a', 'b', 'c', 'D', 'e']
>>> max(L)
max(list) # Maximum value (in order)
'e'
>>> min(L)
min(list) # Minimum value (in order)
'D'
>>> L.reverse()
List.reverse() # reverses the order of the items in the list
>>> L, ['e', 'D', 'c', 'b', 'a']
>>> L.sort()
sort() list # sort the list (in ascending order)
>>> L, ['D', 'a', 'b', 'c', 'e']
>>> [6, 7, 6, 7, 6].count(6)
List.count(item) # count occurrences of an item
3
# adding elements from another >>> L.extend([6, 7, 6, 7, 6])
list.extend(list)
list at the end (concatenation) >>> L, ['b', 'c', 'd', 'd', 'e' , 6, 7, 6, 7, 6]

Parcourir une liste python

8.2 Exercise.
Given the list of students' grades:
Notes = [12 , 04 , 14 , 11 , 18 , 13 , 07, 10 , 05 , 09 , 15 , 08 , 14 , 16]
Write a Python script that allows:
- Create a list of admitted students containing only grades above the average (grades >= 10).
- Calculate and display the number of even elements in the grade list.

PW N°03 : Matrices and Vectors Page - 5 -

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy