0% found this document useful (0 votes)
26 views12 pages

Mmds

This document provides code to perform and demonstrate linear algebra operations like matrix multiplication, LU decomposition, eigenvalue decomposition, and more using NumPy and SciPy. It includes code to calculate the inverse, determinant, rank, transpose, and reduced row echelon form of matrices. Various linear algebra functions like inverse, dot product, trace, eigenvalues and vectors, LU decomposition, and matrix multiplication are applied to example matrices.

Uploaded by

Good Boy
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)
26 views12 pages

Mmds

This document provides code to perform and demonstrate linear algebra operations like matrix multiplication, LU decomposition, eigenvalue decomposition, and more using NumPy and SciPy. It includes code to calculate the inverse, determinant, rank, transpose, and reduced row echelon form of matrices. Various linear algebra functions like inverse, dot product, trace, eigenvalues and vectors, LU decomposition, and matrix multiplication are applied to example matrices.

Uploaded by

Good Boy
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/ 12

https://numpy.

org/doc/stable/reference/generated/
numpy.linalg.svd.html
import numpy as np
n = int(input());a=[]
for i in range(n):
l = []
for j in range(n):
l.append(int(input()))
a.append(l)
A = np.array(a)
np.asarray(a)

array([[1, 2],
[3, 4]])

import numpy.linalg

from numpy.linalg import *


from numpy import *
inv(A)

array([[-2. , 1. ],
[ 1.5, -0.5]])

print(np.dot(A,inv(A)))

[[1.0000000e+00 0.0000000e+00]
[8.8817842e-16 1.0000000e+00]]

a = np.array([[1,1,1],[0,2,5],[2,5,-1]])
ainv = np.linalg.inv(a)

b = np.array([[6],[-4],[27]])
x = np.linalg.solve(a,b)
x = np.dot(ainv, b)
x

array([[ 5.],
[ 3.],
[-2.]])

matrix_rank(A)

np.transpose(A)
A.transpose()

array([[1, 3],
[2, 4]])
# import sympy
from sympy import *

M = Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]])


print("Matrix : {} ".format(M))

# Use sympy.rref() method


M_rref = M.rref()

print("The Row echelon form of matrix M and the pivot columns :


{}".format(M_rref))

Matrix : Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]])


The Row echelon form of matrix M and the pivot columns : (Matrix([
[1, 0, 1, 3],
[0, 1, 2/3, 1/3],
[0, 0, 0, 0]]), (0, 1))

import numpy as np

def rref(B, tol=1e-8, debug=False):


A = B.copy()
rows, cols = A.shape
r = 0
pivots_pos = []
row_exchanges = np.arange(rows)
for c in range(cols):
if debug: print( "Now at row", r, "and col", c, "with matrix:");
print( A)

## Find the pivot row:


pivot = np.argmax (np.abs (A[r:rows,c])) + r
m = np.abs(A[pivot, c])
if debug: print( "Found pivot", m, "in row", pivot)
if m <= tol:
## Skip column c, making sure the approximately zero terms are
## actually zero.
A[r:rows, c] = np.zeros(rows-r)
if debug: print( "All elements at and below (", r, ",", c, ")
are zero.. moving on..")
else:
## keep track of bound variables
pivots_pos.append((r,c))

if pivot != r:
## Swap current row and pivot row
A[[pivot, r], c:cols] = A[[r, pivot], c:cols]
row_exchanges[[pivot,r]] = row_exchanges[[r,pivot]]
if debug: print( "Swap row"), r, "with row", pivot, "Now:";
print( A)

## Normalize pivot row


A[r, c:cols] = A[r, c:cols] / A[r, c];

## Eliminate the current column


v = A[r, c:cols]
## Above (before row r):
if r > 0:
ridx_above = np.arange(r)
A[ridx_above, c:cols] = A[ridx_above, c:cols] - np.outer(v,
A[ridx_above, c]).T
if debug: print( "Elimination above performed:"); print( A)
## Below (after row r):
if r < rows-1:
ridx_below = np.arange(r+1,rows)
A[ridx_below, c:cols] = A[ridx_below, c:cols] - np.outer(v,
A[ridx_below, c]).T
if debug: print( "Elimination below performed:"); print( A)
r += 1
## Check if done
if r == rows:
break
return (A, pivots_pos, row_exchanges)

def ToReducedRowEchelonForm(M):
## If M is empty, no need to proceed, and just return
if not M: return
## if rows are less than column, lead variable used to check that,
for every row increment, lead incremented by 1 and if its value
greater than or equal to column count, return
lead = 0
## No of rows in Matrix
rowCount = len(M)
## No of columns in Matrix
columnCount = len(M[0])
## Iterating row of Matrix
for r in range(rowCount):
if lead >= columnCount:
return
i = r
## If leading element of that row itself 0, check next row's
leading element if its zero or not
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
## Swap Rows i and r --> will happen only if lead element M[i]
[lead] equal to 0 and i is not equal to rowCount
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
## Making Lead Entry -- 1
M[r] = [ mrx / float(lv) for mrx in M[r]]
## Each column will have single Non-Zero entry
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
return M

# install sympy
! pip install sympy

## CODE TO FIND RANK OF MATRIX


# import sympy
from sympy import *

M = Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]])


print("Matrix : {} ".format(M))

# Use sympy.rref() method


M_RREF = M.rref()
print(M_RREF[0])
print("Rank of Matrix {}".format(len(np.nonzero(M_RREF)[0])))

Requirement already satisfied: sympy in c:\users\vansh\appdata\local\


programs\python\python39\lib\site-packages (1.11.1)
Requirement already satisfied: mpmath>=0.19 in c:\users\vansh\appdata\
local\programs\python\python39\lib\site-packages (from sympy) (1.2.1)

[notice] A new release of pip available: 22.1.2 -> 22.2.2


[notice] To update, run: python.exe -m pip install --upgrade pip
Matrix : Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]])
Matrix([[1, 0, 1, 3], [0, 1, 2/3, 1/3], [0, 0, 0, 0]])
Rank of Matrix 2

A.T # Transpose

array([[1, 3],
[2, 4]])

# import sympy
from sympy import *

M = Matrix([[14, 0, 11, 3], [22, 23, 4, 7], [-12, -34, -3, -4]])
print("Matrix : {} ".format(M))

# Use sympy.columnspace() method


M_columnspace = M.columnspace()

print("Columnspace of a matrix : {}".format(M_columnspace))

Matrix : Matrix([[14, 0, 11, 3], [22, 23, 4, 7], [-12, -34, -3, -4]])
Columnspace of a matrix : [Matrix([
[ 14],
[ 22],
[-12]]), Matrix([
[ 0],
[ 23],
[-34]]), Matrix([
[11],
[ 4],
[-3]])]

np.trace(A)
A==[1,2]

array([[ True, True],


[False, False]])

Eigen
import numpy as np
from numpy.linalg import eig

a = np.array([[0, 2],
[2, 3]])
w,v=eig(a)
print('E-value:', w)
print('E-vector', v)

a = np.array([[2, 2, 4],
[1, 3, 5],
[2, 3, 4]])
w,v=eig(a)
print('E-value:', w)
print('E-vector', v)

w, v = eig(np.diag((1, 2, 3)))
print(w,"\n",v)

# a = np.array([[1, 1j], [-1j, 1]])


# eig(a)

E-value: [-1. 4.]


E-vector [[-0.89442719 -0.4472136 ]
[ 0.4472136 -0.89442719]]
E-value: [ 8.80916362 0.92620912 -0.73537273]
E-vector [[-0.52799324 -0.77557092 -0.36272811]
[-0.604391 0.62277013 -0.7103262 ]
[-0.59660259 -0.10318482 0.60321224]]
[1. 2. 3.]
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]

import pprint
import scipy
import scipy.linalg as ala
pprint.pprint(ala.lu(A))
A

(array([[0., 1.],
[1., 0.]]),
array([[1. , 0. ],
[0.33333333, 1. ]]),
array([[3. , 4. ],
[0. , 0.66666667]]))

array([[1, 2],
[3, 4]])

import pprint
import scipy
import scipy.linalg # SciPy Linear Algebra Library

A = np.array([ [7, 3, -1, 2], [3, 8, 1, -4], [-1, 1, 4, -1], [2, -4, -
1, 6] ])
P, L, U = scipy.linalg.lu(A)

print( "A:")
pprint.pprint(A)

print( "P:")
pprint.pprint(P)

print( "L:")
pprint.pprint(L)

print( "U:")
pprint.pprint(U)

A:
array([[ 7, 3, -1, 2],
[ 3, 8, 1, -4],
[-1, 1, 4, -1],
[ 2, -4, -1, 6]])
P:
array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
L:
array([[ 1. , 0. , 0. , 0. ],
[ 0.42857143, 1. , 0. , 0. ],
[-0.14285714, 0.21276596, 1. , 0. ],
[ 0.28571429, -0.72340426, 0.08982036, 1. ]])
U:
array([[ 7. , 3. , -1. , 2. ],
[ 0. , 6.71428571, 1.42857143, -4.85714286],
[ 0. , 0. , 3.55319149, 0.31914894],
[ 0. , 0. , 0. , 1.88622754]])

import pprint

def mult_matrix(M, N):


"""Multiply square matrices of same dimension M and N"""

# Converts N into a list of tuples of columns

tuple_N = zip(*N)

# Nested list comprehension to calculate matrix multiplication

return [[sum(el_m * el_n for el_m, el_n in zip(row_m, col_n)) for


col_n in tuple_N] for row_m in M]

def pivot_matrix(M):
"""Returns the pivoting matrix for M, used in Doolittle's
method."""
m = len(M)

# Create an identity matrix, with floating point values

id_mat = [[float(i ==j) for i in range(m)] for j in range(m)]

# Rearrange the identity matrix such that the largest element of

# each column of M is placed on the diagonal of of M

for j in range(m):
row = max(range(j, m), key=lambda i: abs(M[i][j]))
if j != row:
# Swap the rows

id_mat[j], id_mat[row] = id_mat[row], id_mat[j]


return id_mat

def lu_decomposition(A):
"""Performs an LU Decomposition of A (which must be square)

into PA = LU. The function returns P, L and U."""


n = len(A)

# Create zero matrices for L and U

L = [[0.0] * n for i in range(n)]


U = [[0.0] * n for i in range(n)]

# Create the pivot matrix P and the multipled matrix PA

P = pivot_matrix(A)
PA = mult_matrix(P, A)

# Perform the LU Decomposition

for j in range(n):
# All diagonal entries of L are set to unity

L[j][j] = 1.0

# LaTeX: u_{ij} = a_{ij} - \sum_{k=1}^{i-1} u_{kj} l_{ik}

for i in range(j+1):
s1 = sum(U[k][j] * L[i][k] for k in range(i))
U[i][j] = PA[i][j] - s1

# LaTeX: l_{ij} = \frac{1}{u_{jj}} (a_{ij} - \sum_{k=1}^{j-1}


u_{kj} l_{ik} )

for i in range(j, n):


s2 = sum(U[k][j] * L[i][k] for k in range(j))
L[i][j] = (PA[i][j] - s2) / U[j][j]

print( "P:")
pprint.pprint(P)

print( "L:")
pprint.pprint(L)

print( "U:")
pprint.pprint(U)
return #(P, L, U)
A = [[7, 3, -1, 2], [3, 8, 1, -4], [-1, 1, 4, -1], [2, -4, -1, 6]]
# P, L, U = lu_decomposition(A)
lu_decomposition(A)
print( "A:")
pprint.pprint(A)

# print( "P:")
# pprint.pprint(P)

# print( "L:")
# pprint.pprint(L)

# print( "U:")
# pprint.pprint(U)

C:\Users\vansh\AppData\Local\Temp/ipykernel_18508/4260261951.py:10:
DeprecationWarning: Calling np.sum(generator) is deprecated, and in
the future will give a different result. Use
np.sum(np.fromiter(generator)) or the python sum builtin instead.
return [[sum(el_m * el_n for el_m, el_n in zip(row_m, col_n)) for
col_n in tuple_N] for row_m in M]
C:\Users\vansh\AppData\Local\Temp/ipykernel_18508/4260261951.py:49:
DeprecationWarning: Calling np.sum(generator) is deprecated, and in
the future will give a different result. Use
np.sum(np.fromiter(generator)) or the python sum builtin instead.
s1 = sum(U[k][j] * L[i][k] for k in range(i))
C:\Users\vansh\AppData\Local\Temp/ipykernel_18508/4260261951.py:54:
DeprecationWarning: Calling np.sum(generator) is deprecated, and in
the future will give a different result. Use
np.sum(np.fromiter(generator)) or the python sum builtin instead.
s2 = sum(U[k][j] * L[i][k] for k in range(j))

----------------------------------------------------------------------
-----
IndexError Traceback (most recent call
last)
~\AppData\Local\Temp/ipykernel_18508/4260261951.py in <module>
68 A = [[7, 3, -1, 2], [3, 8, 1, -4], [-1, 1, 4, -1], [2, -4, -1,
6]]
69 # P, L, U = lu_decomposition(A)
---> 70 lu_decomposition(A)
71 print( "A:")
72 pprint.pprint(A)

~\AppData\Local\Temp/ipykernel_18508/4260261951.py in
lu_decomposition(A)
53 for i in range(j, n):
54 s2 = sum(U[k][j] * L[i][k] for k in range(j))
---> 55 L[i][j] = (PA[i][j] - s2) / U[j][j]
56
57 print( "P:")

IndexError: list index out of range

import pprint
import scipy
import scipy.linalg # SciPy Linear Algebra Library

A = np.array([[6, 3, 4, 8], [3, 6, 5, 1], [4, 5, 10, 7], [8, 1, 7,


25]])
L = scipy.linalg.cholesky(A, lower=True)
U = scipy.linalg.cholesky(A, lower=False)

print ("A:")
pprint.pprint(A)

print( "L:")
pprint.pprint(L)

print ("U:")
pprint.pprint(U)

A:
array([[ 6, 3, 4, 8],
[ 3, 6, 5, 1],
[ 4, 5, 10, 7],
[ 8, 1, 7, 25]])
L:
array([[ 2.44948974, 0. , 0. , 0. ],
[ 1.22474487, 2.12132034, 0. , 0. ],
[ 1.63299316, 1.41421356, 2.30940108, 0. ],
[ 3.26598632, -1.41421356, 1.58771324, 3.13249102]])
U:
array([[ 2.44948974, 1.22474487, 1.63299316, 3.26598632],
[ 0. , 2.12132034, 1.41421356, -1.41421356],
[ 0. , 0. , 2.30940108, 1.58771324],
[ 0. , 0. , 0. , 3.13249102]])

np.linalg.cholesky(A)

array([[ 2.44948974, 0. , 0. , 0. ],
[ 1.22474487, 2.12132034, 0. , 0. ],
[ 1.63299316, 1.41421356, 2.30940108, 0. ],
[ 3.26598632, -1.41421356, 1.58771324, 3.13249102]])

# Python3 program to decompose


# a matrix using Cholesky
# Decomposition
import math
MAX = 100;
def Cholesky_Decomposition(matrix, n):

lower = [[0 for x in range(n + 1)]


for y in range(n + 1)];

# Decomposing a matrix
# into Lower Triangular
for i in range(n):
for j in range(i + 1):
sum1 = 0;

# summation for diagonals


if (j == i):
for k in range(j):
sum1 += pow(lower[j][k], 2);
lower[j][j] = int(math.sqrt(matrix[j][j] -
sum1));
else:

# Evaluating L(i, j)
# using L(j, j)
for k in range(j):
sum1 += (lower[i][k] *lower[j][k]);
if(lower[j][j] > 0):
lower[i][j] = int((matrix[i][j] - sum1) /
lower[j]
[j]);

# Displaying Lower Triangular


# and its Transpose
print("Lower Triangular\t\tTranspose");
for i in range(n):

# Lower Triangular
for j in range(n):
print(lower[i][j], end = "\t");
print("", end = "\t");

# Transpose of
# Lower Triangular
for j in range(n):
print(lower[j][i], end = "\t");
print("");

# Driver Code
n = 3;
matrix = [[4, 12, -16],
[12, 37, -43],
[-16, -43, 98]];
Cholesky_Decomposition(matrix, n);

# This code is contributed by mits

Lower Triangular Transpose


2 0 0 2 6 -8
6 1 0 0 1 5
-8 5 3 0 0 3

u, s, vh = np.linalg.svd(a, full_matrices=False)
np.linalg.svd(a, full_matrices=True)

(array([[-0.52157957, 0.51176432, -0.68268004],


[-0.62993653, -0.7706383 , -0.09641875],
[-0.57544307, 0.37975505, 0.72432823]]),
array([9.30064272, 1.06283875, 0.60697515]),
array([[-0.30363297, -0.50096516, -0.81045724],
[ 0.95254376, -0.14030457, -0.27013886],
[-0.02161931, 0.85401905, -0.51979233]]))

u.shape, s.shape, vh.shape

((3, 3), (3,), (3, 3))

np.allclose(a, np.dot(u * s, vh))

True

smat = np.diag(s)
np.allclose(a, np.dot(u, np.dot(smat, vh)))

True

You might also like