0
0
SciPydata~5 mins

Matrix creation and operations in SciPy

Choose your learning style9 modes available
Introduction

Matrices help organize numbers in rows and columns. We use them to solve problems like systems of equations or transformations.

When you want to represent data in rows and columns, like a spreadsheet.
When solving multiple equations at once.
When performing transformations in graphics or physics.
When calculating relationships between variables in data science.
Syntax
SciPy
import numpy as np
from scipy import linalg

# Create a matrix
A = np.array([[1, 2], [3, 4]])

# Matrix operations examples
B = np.array([[5, 6], [7, 8]])

# Addition
C = A + B

# Multiplication
D = A @ B

# Inverse
A_inv = linalg.inv(A)

We use numpy to create matrices because scipy builds on it.

Matrix multiplication uses @ symbol or np.dot().

Examples
This creates a 3 by 3 matrix filled with zeros.
SciPy
import numpy as np

# Create a 3x3 zero matrix
Z = np.zeros((3,3))
An identity matrix has 1s on the diagonal and 0s elsewhere.
SciPy
import numpy as np

# Create an identity matrix of size 4
I = np.eye(4)
The determinant helps check if a matrix is invertible.
SciPy
import numpy as np
from scipy import linalg

A = np.array([[1, 2], [3, 4]])

# Calculate determinant
det = linalg.det(A)
Sample Program

This program creates two matrices, adds and multiplies them, then finds the inverse and determinant of the first matrix.

SciPy
import numpy as np
from scipy import linalg

# Create two matrices
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

# Add matrices
C = A + B

# Multiply matrices
D = A @ B

# Calculate inverse of A
A_inv = linalg.inv(A)

# Calculate determinant of A
det_A = linalg.det(A)

print('Matrix A:')
print(A)
print('\nMatrix B:')
print(B)
print('\nA + B:')
print(C)
print('\nA * B:')
print(D)
print('\nInverse of A:')
print(A_inv)
print(f'\nDeterminant of A: {det_A}')
OutputSuccess
Important Notes

Matrix multiplication is not the same as element-wise multiplication.

Not all matrices have inverses; check determinant first.

Summary

Matrices organize data in rows and columns.

Use numpy to create and manipulate matrices.

Scipy provides tools like inverse and determinant calculations.