59 lines
2.4 KiB
Python
59 lines
2.4 KiB
Python
import numpy as np
|
|
"""
|
|
This script demonstrates basic linear algebra operations using NumPy, including:
|
|
1. Matrix transposition.
|
|
2. Dot product of vectors using both np.dot() and the @ operator.
|
|
3. Matrix multiplication using both np.dot() and the @ operator.
|
|
4. Calculation of weighted final scores for students based on exam scores and subject coefficients.
|
|
Sections:
|
|
- Matrix and vector creation and display.
|
|
- Transposing matrices.
|
|
- Dot product and matrix multiplication.
|
|
- Application example: computing weighted final scores for students.
|
|
Variables:
|
|
- matrix: 2D NumPy array representing a matrix.
|
|
- transposed_matrix: Transposed version of 'matrix'.
|
|
- vector_1, vector_2: 1D NumPy arrays representing vectors.
|
|
- matrix_1, matrix_2: 2D NumPy arrays for matrix multiplication.
|
|
- exams_scores: 2D NumPy array of students' exam scores.
|
|
- coefficients: 1D NumPy array of subject weights.
|
|
- final_scores: 1D NumPy array of weighted final scores for each student.
|
|
"""
|
|
|
|
matrix = np.array([[1, 2, 3], [4, 5, 6]])
|
|
print(f'Original matrix:\n{matrix}')
|
|
# Transposing a matrix
|
|
transposed_matrix = matrix.T
|
|
print(f'\nTransposed matrix:\n{transposed_matrix}')
|
|
|
|
|
|
vector_1 = np.array([1, 2, 3])
|
|
print(f'\nVector 1: {vector_1}')
|
|
vector_2 = np.array([4, 5, 6])
|
|
print(f'Vector 2: {vector_2}')
|
|
# Dot product using the dot() function
|
|
print(f'\nDot product (dot function): {np.dot(vector_1, vector_2)}')
|
|
# Dot product using the @ operator
|
|
print(f'Dot product (@ operator): {vector_1 @ vector_2}')
|
|
matrix_1 = np.array([[1, 2, 3], [4, 5, 6]])
|
|
print(f'\nMatrix 1:\n{matrix_1}')
|
|
matrix_2 = np.array([[7, 10], [8, 11], [9, 12]])
|
|
print(f'\nMatrix 2:\n{matrix_2}')
|
|
# Matrix multiplication using the dot() function
|
|
print(f'\nMatrix multiplication (dot function):\n{np.dot(matrix_1, matrix_2)}')
|
|
# Matrix multiplication using the @ operator
|
|
print(f'\nMatrix multiplication (@ operator):\n{matrix_1 @ matrix_2}')
|
|
|
|
|
|
# Task: Simulated exams scores of three students from three subjects
|
|
exams_scores = np.array([[100, 82, 95], [56, 70, 90], [45, 98, 66]])
|
|
print
|
|
coefficients = np.array([0.5, 0.3, 0.2])
|
|
print(f'\nExams scores:\n{exams_scores}')
|
|
print(f'Coefficients:\n{coefficients}')
|
|
# Calculate the dot product between exam_scores and coefficients
|
|
final_scores = np.dot(exams_scores, coefficients)
|
|
print(f'\nFinal scores (dot function):\n{final_scores}')
|
|
|
|
final_scores = (exams_scores @ coefficients)
|
|
print(f'\nFinal scores (@ operator):\n{final_scores}') |