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

NumPy Array Operations Guide

The document provides a comprehensive guide on using NumPy for array creation, operations, statistics, reshaping, indexing, and applying functions. It also covers random number generation, linear algebra applications including matrix multiplication, solving linear systems, matrix decomposition, eigenvalues, determinants, inversions, norms, and rank determination. Each section includes code examples and outputs to illustrate the functionality of NumPy.

Uploaded by

Harshitha Reddy
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)
10 views5 pages

NumPy Array Operations Guide

The document provides a comprehensive guide on using NumPy for array creation, operations, statistics, reshaping, indexing, and applying functions. It also covers random number generation, linear algebra applications including matrix multiplication, solving linear systems, matrix decomposition, eigenvalues, determinants, inversions, norms, and rank determination. Each section includes code examples and outputs to illustrate the functionality of NumPy.

Uploaded by

Harshitha Reddy
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

import numpy as np

############## 1. CREATING ARRAYS . $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

#2. Creating Arrays


#Creating a 1D array:

a = [Link]([1, 2, 3, 4])
print(a)

[1 2 3 4]

b = [Link]([[1, 2, 3], [4, 5, 6]])


print(b)

[[1 2 3]
[4 5 6]]

# Generates ..zeros as per the dimensions feed by the user.


c = [Link]((2, 3))
print(c)

[[0. 0. 0.]
[0. 0. 0.]]

# Generates ..ones as per the dimensions feed by the user.


d = [Link]((3, 2))
print(d)

[[1. 1.]
[1. 1.]
[1. 1.]]

e = [Link]((2, 2), 7)
print(e)

[[7 7]
[7 7]]

f = [Link](20) # Equivalent to range(10)


print(f)

[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]

g = [Link](0, 1, 5) # 5 values from 0 to 1


print(g)

[0. 0.25 0.5 0.75 1. ]

######################### Array Operations..............$$$$$$$$$$$$$

h = [Link]([1, 2, 3])
i = [Link]([4, 5, 6])
array_addition = h + i
print(array_addition)

[5 7 9]

product_array = h * i #Elementwise multiplication


print(product_array)

[ 4 10 18]

j = [Link]([[1, 2], [3, 4]]) #Matrix multiplication:


k = [Link]([[5, 6], [7, 8]])
k [Link]([[5, 6], [7, 8]])
matrix_product = [Link](j, k)
print(matrix_product)

[[19 22]
[43 50]]

## 4. Array Statistics

#Mean of an array:
mean_val = [Link](f)
print(mean_val)

9.5

#Standard deviation of an array:

std_dev = [Link](f)
print(std_dev)

5.766281297335398

#Sum of array elements:

total_sum = [Link](f)
print(total_sum)

190

### 5. Reshaping Arrays

reshaped = [Link](f, (4, 5)) ##Reshape a 1D array to 2D:


print(reshaped)

[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]

#Flatten a 2D array:
flattened = [Link]()
print(flattened)

[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]

#### 6. Array Indexing and Slicing

element = b[1, 2] # Element at row 1, column 2


print(element)

slice_array = b[0:2, 1:3] #Slicing an array:


print(slice_array)

[[2 3]
[5 6]]

#### 7. Applying Functions

# Apply a function to each element:

squared_array = [Link](f)
print(squared_array)

[0. 1. 1.41421356 1.73205081 2. 2.23606798


2.44948974 2.64575131 2.82842712 3. 3.16227766 3.31662479
3.46410162 3.60555128 3.74165739 3.87298335 4. 4.12310563
4.24264069 4.35889894]
# Apply a function along an axis:

print(b)
print()

sum_axis0 = [Link](b, axis=0) # Sum along rows


print(sum_axis0)

sum_axis1 = [Link](b, axis=1) # Sum along columns


print(sum_axis1)

[[1 2 3]
[4 5 6]]

[5 7 9]
[ 6 15]

### 8. Random Numbers

random_ints = [Link](0, 10, size=(2, 3)) # Generate random integer


print(random_ints)

[[2 6 0]
[6 2 0]]

random_floats = [Link]((2, 2)) # Generate Random Floats


print(random_floats)

[[0.15120192 0.46644157]
[0.40234905 0.27096769]]

####### LINEAR ALGEBRA APPLICATIONS $$$$$$$$$$$$$$$

### Matrix Multiplication


#Matrix multiplication is fundamental in linear algebra. NumPy uses the [Link]() function or the @ operator for this purpose.

A = [Link]([[1, 2], [3, 4]])


B = [Link]([[5, 6], [7, 8]])

# Matrix multiplication
C = [Link](A, B)
# Alternatively: C = A @ B

print(C)

[[19 22]
[43 50]]

#Solving Linear Systems


#You can solve systems of linear equations

#Ax=b using the [Link]() function.

A = [Link]([[3, 2], [1, 2]])


b = [Link]([5, 6])

# Solve for x
x = [Link](A, b)
print(x)

[-0.5 3.25]
#3. Matrix Decomposition
#Matrix decompositions such as LU decomposition, QR decomposition, and Singular Value Decomposition (SVD) are crucial in numerical analy

#LU Decomposition
from [Link] import lu

A = [Link]([[3, 2], [1, 2]])

# LU decomposition
P, L, U = lu(A)
print("P:", P)
print("L:", L)
print("U:", U)

P: [[1. 0.]
[0. 1.]]
L: [[1. 0. ]
[0.33333333 1. ]]
U: [[3. 2. ]
[0. 1.33333333]]

#4. Eigenvalues and Eigenvectors


# Finding eigenvalues and eigenvectors is essential in various fields, including stability analysis and principal component analysis (PC
#Ax=(Lambda)x x is eigen vector, lambda is eign value

A = [Link]([[4, 2], [1, 3]])

# Compute eigenvalues and eigenvectors


eigenvalues, eigenvectors = [Link](A)
print("Eigenvalues:", eigenvalues)
print("Eigenvectors:", eigenvectors)

Eigenvalues: [5. 2.]


Eigenvectors: [[ 0.89442719 -0.70710678]
[ 0.4472136 0.70710678]]

#5. Matrix Determinant


#The determinant of a matrix is a scalar value that can be used to determine if a matrix is invertible and other properties.

A = [Link]([[1, 2], [3, 4]])

# Compute determinant
det = [Link](A)
print("Determinant:", det)

Determinant: -2.0000000000000004

# 6. Matrix Inversion
# Inverting a matrix is necessary for solving linear systems and other applications.

A = [Link]([[1, 2], [3, 4]])

# Compute the inverse


A_inv = [Link](A)
print("Inverse of A:\n", A_inv)

Inverse of A:
[[-2. 1. ]
[ 1.5 -0.5]]

#7. Norms
#Matrix norms and vector norms help in assessing the magnitude of vectors and matrices.

v = [Link]([1, 2, 3])

# Compute L2 norm (Euclidean norm)


norm_v = [Link](v)
print("Norm of v:", norm_v)

Norm of v: 3.7416573867739413
##8. Rank of a Matrix
## Determining the rank of a matrix helps in understanding its properties.

A = [Link]([[6, 8], [3, 4]])

# Compute the rank


rank_A = [Link].matrix_rank(A)
print("Rank of A:", rank_A)

Rank of A: 1

Start coding or generate with AI.

Common questions

Powered by AI

NumPy supports linear algebra applications by providing efficient tools for matrix operations, such as matrix multiplication using np.dot() or the @ operator, solving linear systems with np.linalg.solve(), and computing decompositions like LU. These capabilities allow users to conduct complex linear algebra operations efficiently, contributing significantly to fields such as engineering, physics, economics, and machine learning, where precise mathematical transformations and manipulations are necessary .

NumPy can solve a system of linear equations using the np.linalg.solve() function, which requires a coefficient matrix and a constant vector. This function provides an efficient and straightforward way to find solutions to linear equations by leveraging optimized linear algebra operations. The main advantages include handling large data efficiently, ensuring numerical stability, and benefiting from NumPy's integration with other scientific computing libraries .

NumPy offers methods such as np.reshape() for altering the dimensions of arrays and np.flatten() for reducing multidimensional arrays into a single dimension. These methods enhance data processing by allowing flexible organization and transformation of data structures, facilitating efficient data management and manipulation in various data processing and analytic tasks without altering the underlying data entries .

Matrix multiplication in NumPy is achieved using the np.dot() function or the @ operator, where the sum of products of rows and columns are computed, resulting in a matrix product. This is different from elementwise multiplication, which multiplies corresponding elements of arrays directly. Matrix multiplication is fundamental in linear algebra applications, enabling operations such as transformations, rotations, and solving linear systems, whereas elementwise operations are used for element-specific calculations .

Random number generation in NumPy, facilitated through functions like np.random.randint() and np.random.random(), provides tools for statistical simulations and probabilistic modeling. This capability is crucial for Monte Carlo simulations, random sampling, and stochastic processes, offering reproducibility and efficiency in generating pseudo-random numbers for testing, modeling, and hypothesis validation in scientific research and analysis .

Matrix decompositions, such as LU decomposition, are critical in numerical analysis for solving linear systems, optimizing performance, and aiding in computational stability. In NumPy, LU decomposition can be implemented using scipy.linalg's lu function, which decomposes a matrix into a product of a lower triangular matrix (L), upper triangular matrix (U), and a permutation matrix (P), facilitating more efficient and stable computational processes .

The rank of a matrix is a measure of its non-degeneracy, which indicates the maximum number of linearly independent row or column vectors present in the matrix. This concept is crucial for determining whether a system of equations has a unique solution. In NumPy, the rank is determined using np.linalg.matrix_rank, which helps in understanding the matrix's properties and its associated linear systems’ solutions .

Eigenvalues and eigenvectors are used in fields such as stability analysis and principal component analysis to understand characteristic directions and magnitudes of transformations represented by matrices. In NumPy, they are computed using np.linalg.eig, which returns the eigenvalues and eigenvectors of a square matrix, facilitating analysis of various dynamic behaviors and transformations in applied mathematics .

Applying functions along an axis in a NumPy array involves performing operations such as summation, mean, or square root across specified dimensions (rows or columns). This is executed by setting the axis parameter in functions like np.sum(). It simplifies processes like aggregate calculations and statistical analysis, enabling concise and efficient data manipulation across large datasets .

The determinant of a matrix is a scalar value that indicates whether a matrix is invertible and provides insights into its properties, such as volume scaling factor. The inverse of a matrix, when it exists, is used in solving systems of linear equations and other operations requiring reversible transformations. NumPy facilitates these computations via np.linalg.det() and np.linalg.inv(), providing precise and efficient tools for determining the matrix's invertibility and constructing its inverse, important in numerous linear algebra applications .

You might also like