Vectors and Matrices
Learn how to represent vectors and matrices using NumPy arrays. Understand vector dimensions, matrix rows and columns, matrix properties, vector operations, and basic linear algebra concepts through practical examples and numerical datasets.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Understand vectors and matrices in numerical computing.
- Create one-dimensional and two-dimensional NumPy arrays.
- Identify vector and matrix dimensions.
- Access individual elements using indexing.
- Perform basic vector arithmetic.
- Understand matrix rows, columns, shape, and size.
- Calculate vector magnitude and distance.
- Understand the difference between element-wise multiplication and matrix multiplication.
- Use vectors and matrices in practical data analysis problems.
2. Introduction to Vectors and Matrices
Vectors and matrices are fundamental concepts in linear algebra. They are widely used in data science, machine learning, engineering, statistics, computer graphics, and scientific computing.
A vector is an ordered collection of numerical values. A matrix is a rectangular arrangement of values organized into rows and columns.
Vector Example
A vector containing three values can be represented as:
This vector contains three elements and can be represented using a one-dimensional NumPy array.
Matrix Example
A matrix containing two rows and three columns is:
This matrix contains six elements arranged in two rows and three columns.
ndarray data structure.
A vector commonly uses one dimension, while a matrix uses
two dimensions.
3. Creating a Vector in NumPy
A one-dimensional NumPy array can represent a vector.
Use np.array() to create a vector from a
Python list.
Output:
The vector has one dimension, a shape of (5,),
and five elements.
A one-dimensional vector stores values in a single sequence.
4. Creating a Matrix in NumPy
A two-dimensional NumPy array can represent a matrix. Each inner list represents one row, and each value within that row occupies a column.
Output:
The matrix has two dimensions, two rows, three columns, and six total elements.
(2, 3) contains two rows and three columns.
The shape is reported in the order
(rows, columns).
5. Understanding Matrix Rows and Columns
Rows and columns help organize matrix data. For example, a student marks matrix can store one student per row and one subject per column.
Output:
NumPy uses zero-based indexing, so the first row has index 0 and the first column has index 0.
Reading Matrix Indexing
| Expression | Meaning |
|---|---|
marks[0] |
Selects the first row. |
marks[1] |
Selects the second row. |
marks[:, 0] |
Selects the first column. |
marks[:, 1] |
Selects the second column. |
marks[1, 2] |
Selects the value in the second row and third column. |
6. Accessing Vector Elements
Vector elements can be accessed using their index. NumPy starts indexing at zero.
Output:
Positive indexing starts at zero, while negative indexing counts backward from the end of the array.
7. Basic Vector Arithmetic
NumPy supports arithmetic operations on vectors. When two vectors have compatible shapes, arithmetic operations such as addition, subtraction, and element-wise multiplication can be performed.
Output:
These operations are element-wise. Each element in the first vector is combined with the corresponding element in the second vector.
* operator
performs element-wise multiplication for NumPy arrays.
It does not perform matrix multiplication.
8. Scalar Operations on Vectors
A scalar is a single numerical value. NumPy allows a scalar to be applied to every element of a vector.
Output:
The scalar is applied to each element without requiring an explicit Python loop.
9. Vector Magnitude
The magnitude, or Euclidean norm, measures the length
of a vector. For a vector with components
[x, y], its magnitude is:
Magnitude = square root of the sum of squared components.
For a vector with components [3, 4],
the magnitude is 5.
Output:
NumPy's np.linalg.norm() calculates the
Euclidean norm by default for a one-dimensional vector.
Magnitude of a Three-Dimensional Vector
Output:
The magnitude is 7 because the sum of the squared components is 49, whose square root is 7.
10. Calculating Distance Between Vectors
The Euclidean distance between two vectors is the magnitude of their difference. It measures how far apart the two vectors are in numerical space.
Output:
This technique is useful in geometry, clustering, machine learning, and numerical comparisons.
11. Matrix Arithmetic
Matrices of compatible shapes can be added and subtracted element by element. Scalar operations can also be applied to every matrix element.
Output:
Addition and subtraction require compatible shapes.
In this example, both matrices have shape
(2, 2).
12. Element-Wise Multiplication vs Matrix Multiplication
NumPy supports two different multiplication concepts. Element-wise multiplication multiplies corresponding elements, while matrix multiplication combines rows and columns according to linear algebra rules.
Element-Wise Multiplication
Output:
Matrix Multiplication
Output:
The @ operator performs matrix multiplication.
The np.matmul() function can also be used.
* for
element-wise multiplication and @ for
matrix multiplication.
13. Matrix Transpose
The transpose of a matrix exchanges its rows and columns.
For a two-dimensional NumPy array, use the
.T attribute.
Output:
The original matrix has two rows and three columns. Its transpose has three rows and two columns.
14. Identity and Zero Matrices
NumPy provides convenient functions to create matrices with common mathematical structures.
np.zeros() creates an array filled with zeros.
np.eye() creates an identity matrix, and
np.ones() creates an array filled with ones.
Identity Matrix
An identity matrix contains ones along its main diagonal and zeros elsewhere. For compatible matrices, multiplying by the identity matrix leaves the matrix unchanged.
15. Practical Activity: Student Marks Matrix
Activity Description
Samadhan, Pradnya, and Samiksha are analyzing marks at CIIT TRANING INSTITUTE. Each student has marks for Python, NumPy, and Statistics.
Complete the following tasks:
- Create a two-dimensional array containing the marks.
- Display the matrix shape and dimensions.
- Calculate each student's total marks.
- Calculate each student's average marks.
- Calculate the average marks for each subject.
- Find the highest mark in the matrix.
- Transpose the marks matrix.
Sample Solution
This activity demonstrates how NumPy matrices can organize structured numerical data and support calculations across rows and columns.
16. Common Mistakes and Best Practices
Common Mistakes
- Confusing a one-dimensional vector with a two-dimensional column matrix.
- Forgetting that NumPy indexing starts at zero.
- Confusing rows with columns when reading a matrix shape.
- Using
*when matrix multiplication is required. - Trying to add matrices with incompatible shapes.
- Assuming
shape,size, andndimmean the same thing.
Best Practices
- Use
np.array()to create vectors and matrices. - Check
shapeandndimwhen working with arrays. - Use
axis=0for column-wise aggregation on a two-dimensional array. - Use
axis=1for row-wise aggregation on a two-dimensional array. - Use
@ornp.matmul()for matrix multiplication. - Use
np.linalg.norm()for vector magnitude and Euclidean distance.
17. Practice Exercises
- Create a vector containing ten integers and display its shape, size, and number of dimensions.
- Create a 3 × 3 matrix and display its first row and last column.
- Add and subtract two vectors of equal length.
- Multiply a vector by a scalar and explain the result.
- Calculate the magnitude of the vector
[6, 8]. - Calculate the Euclidean distance between
[1, 2]and[4, 6]. - Create two 2 × 2 matrices and compare element-wise multiplication with matrix multiplication.
- Transpose a 2 × 3 matrix and display the new shape.
- Create an identity matrix of order four.
- Create a student marks matrix for Samadhan, Pradnya, and Samiksha and calculate row and column averages.
Summary
In this lesson, we learned how to represent vectors and matrices using NumPy arrays. We explored one-dimensional and two-dimensional arrays, indexing, matrix rows and columns, array shapes, and dimensions.
We performed vector and matrix arithmetic, distinguished element-wise multiplication from matrix multiplication, calculated vector magnitudes and distances, transposed matrices, and created identity, zero, and ones matrices.
Remember to check array shapes before performing operations, use the appropriate multiplication operator, and understand whether a calculation should operate across rows or columns. These concepts provide the foundation for more advanced NumPy linear algebra.