Olzhas Shalkhar
Olzhas Shalkhar

Reputation: 1

To find an inverse matrix of A with LU decomposition

The task asks me to generate A matrix with 50 columns and 50 rows with a random library of seed 1007092020 in the range [0,1].

import numpy as np
np.random.seed(1007092020)
A = np.random.randint(2, size=(3,3))

Then I have to find an inverse matrix of A with LU decomposition. No idea how to do that.

Upvotes: 0

Views: 2730

Answers (1)

Zain Sarwar
Zain Sarwar

Reputation: 1406

If you need matrix A to be a 50 x 50 matrix with random floating numbers, then you can make that with the following code :

import numpy as np

np.random.seed(1007092020)

A = np.random.random((50,50))

Instead, if you want integers in the range 0,1 (1 included), you can do this

A = np.random.randint(0,2,(50,50))

If you want to compute the inverse using LU decomposition, you can use SciPy. It should be noted that since you are generating random matrices, it is possible that your matrix does not have an inverse. In that case, you can not find the inverse.

Here's some code that will work in case A does have an inverse.

from scipy.linalg import lu
p,l,u = lu(A, permute_l = False)

Now that we have the lower (l) and upper (u) triangular matrices, we can find the inverse of A by the following equation : A^-1 = U^-1 L^-1

l = np.dot(p,l) 
l_inv = np.linalg.inv(l)
u_inv = np.linalg.inv(u)
A_inv = np.dot(u_inv,l_inv)

Upvotes: 2

Related Questions