I'm writing some code which generates a random matrix and then proceeds to find its determinant. This is what I have so far, using the recursive formula for the determinant:
import numpy as np
import random
myarray = []
myinput=input('Choose a value for N:')
N=int(myinput)
for i in range(N):
myarray.append([0.0]*N)
for j in range(N):
for i in range(N):
myarray[i][j] = random.randint(0,100)
M=np.array(myarray)
print(M)
def det(matrix):
determinant=0
a=0
while a<N:
M_0a=np.delete(matrix,0,axis=0)
M_0a=np.delete(M_0a,a,axis=1)
print(M_0a)
a+=1
determinant= determinant + ((-1)**a)*(M[0][a])*det(M_0a)
return determinant
print(det(M))
I've written the function kind of incorrectly as I'm unsure how to proceed. Basically the while loop successively eliminates the rows and columns in the 0th row and ath column, but I guess I need some sort of if statement for the condition that the new matrix is 2x2, thus ending the loop and calculating the base determinant of the 2x2 matrix?
Thanks
Related
I defined the matrix a. Then I wrote an algorithm which turns the matrix a into a lower triangular matrix (I provided the programme below)
The algorithm does work because if I do "print(" ")" at the end of the algorithm I do receive a lower triangular matrix
But when I do "print(a)" directly afterwards (so after the algorithm for the lower triangular matrix)
I still receive the previous matrix a... and then it is not a lower triangular matrix. So I would like the matrix a to "permanently" be a lower triangular matrix, and not just whenever I use this algorithm (with the "print(" ")" at the end)
How can I sort of "change" the matrix a in a way that it stays a lower triangular matrix? I hope I expressed myself well.
Here is my python code:
import numpy as np
s = 5
#s is the number of columns and rows respectively#
a = np.array([[None]*s]*s)
print(a)
#I receive a matrix with 5 columns/rows respectively#
#Calculates number of rows and columns present in given matrix#
rows = len(a);
cols = len(a[0]);
if(rows != cols):
print("Matrix should be a square matrix");
else:
#Performs required operation to convert given matrix into lower triangular matrix
print("Lower triangular matrix: ");
for i in range(0, rows):
for j in range(0, cols):
if(j > i):
print("0"),
else:
print(a[i][j]),
print(" ");
#so far it works perfectly fine. If I use this algorithm I do receive a lower triangular matrix#
print(a)
#my wish was that now that I do print(a) again that it would print the matrix a but as a lower triangular matrix. because of the previous algorithm. but I get the same matrix as I did when I did "print(A)" for the first time.#type here
Keep in mind that printing and assigning values to variables are different actions:
print shows a message on the screen but does not change the value of any variable.
Assignment, such as x = 2 or a[i][j] = 0 changes the value that is stored in that place in memory.
If you want to change the matrix, then you need to use the assignment operator to change the values. In practice you just need to add a[i][j] = 0 in the correct place.
if(j > i):
a[i][j] = 0 # <-- add this line
print("0"),
Now the elements in the upper right part will be set to zero.
Passing a function with parameters arr(array), risk_matrix(square matrix),risk_factor(float value)
def infection(arr,risk_matrix,risk_factor):
arr=arr*risk_factor
tup=np.linalg.eig(arr)
evalue=tup[0]
evector=tup[1]
for i in range (len(arr)):
for j in range (i,len(arr)):
if i==j:
continue
risk_edge=0
for k in range (len(evalue)):
risk_edge=risk_edge+(math.exp(evalue[k])*evector[i][k]*evector[j][k])
risk_matrix[i][j]=risk_edge
risk_matrix[j][i]=risk_edge
return risk_matrix
evalue is nx1 array and evector in nxn array
used array broadcasting, speed is improved. if there is a even better method let me know
def infection(arr,risk_matrix,risk_factor):
arr=arr*risk_factor
tup=np.linalg.eig(arr)
evalue=tup[0]
evector=tup[1]
for i in range (len(arr)):
for j in range (i+1,len(arr)):
risk_edge=(np.exp(evalue)*evector[i]*evector[j]).sum()
risk_matrix[i][j]=risk_edge
risk_matrix[j][i]=risk_edge
return risk_matrix
I try to find a solution to found all the columns permutations of a matrix. So i wrote this code but it doesn't work.
SOLVED:
#! python
import numpy
def permutation(matrix):
if numpy.size(matrix,1) == 1:
return [matrix]
#empty list
m=[]
# Iterate the input(matrix) and calculate the permutation
for i in range(numpy.size(matrix,1)):
column = matrix[:,[i]]
# Extract column[i] or m from the matrix. remMatrix is the remaining matrix
remMatrix = numpy.concatenate((matrix[:,:i], matrix[:,i+1:]), axis=1)
# Generating all permutations where m is the first element
for p in permutation(remMatrix):
m.append(numpy.concatenate([column,p],axis=1))
return m
#driver to test the function
matrix=numpy.matrix('1 2 3; 0 0 0')
for p in permutation(matrix):
print(p)
You did not handle the base case in your recursion. If you pass a matrix with a single column, then permutation returns an empty matrix. That is because line m = numpy.concatenate((column,p),axis=1) will not be reached if remMatrix is empty.
As result m is an empty array once you return it and the print statement is not called.
I also don't fully understand what you're trying to do. Wouldn't there for most matrices be multiple column permutations? Do you want all those matrices concatenated in the end?
I have a list L that is full of vectors, I want to calculate the norm of each of these vectors And add the values to a new list N.
I did the following (problem is it returns a single value.. instead of a list of values with all the different norms ) what should i add?
N = list()
from numpy import linalg as LA
N.append(LA.linalg.norm(L,ord=None))
print(N)
Your current code LA.linalg.norm(L,ord=None) calculates a single norm value for the entire list of vectors. To calculate separate norms for each vector in your L list, you should loop over that list and append each result to the N list, e.g.,
N = list()
from numpy import linalg as LA
for vector in L:
N.append(LA.linalg.norm(vector,ord=None))
print(N)
I have a python function that solves matrix equations using Gaussian elimination with partial pivoting. I've been using it as part of a matrix solving module. When I use the Gaussian elimination function by passing it the matrix, called 'A' (a 2D numpy array), and vector of constants called 'b' (1D numpy array), the function seems to operate globally on the variables passed to it instead of using local variables. I am using the same name for the variables being passed to the function and the variables inside the function, but shouldn't the function be using copies of the variables passed to it?
I think the issue might be with the "tuple exchanges." I know they do funky things with variable referencing but I'm not knowledgable enough to say exactly what is wrong here.
The function:
def Gaussian_eliminiation(A,b):
#Gaussian elimination with scaled partial pivoting
n = len(b)
#make sure the arrays are storing float variables and not integers
if not A.dtype == float or b.dtype == float:
print "Variables may be integers and not floats"
#find scaling factors
s = np.zeros((n,))
for i in range(n):
s[i] = max(abs(A[i,:]))
#eliminate, moving through each pivot row with i
for i in range(n-1):
#put the correct pivot row in place
(_, idx) = max_idx(abs(A[i:n,i])/s[i:n])
idx += i
if(idx != i):
#swap values with tuple exchanges
for j in range(i,n):
(A[i,j],A[idx,j]) = (A[idx,j],A[i,j])
(b[i],b[idx]) = (b[idx],b[i])
(s[i],s[idx]) = (s[idx],s[i])
#use the pivot in row i to work on row j
for j in range(i+1,n):
m = A[j,i]/float(A[i,i])
#operate on the elements of row j and the b vector
A[j,i:] -= m*A[i,i:]
b[j] -= m*b[i]
if(A[n-1,n-1] == 0):
print "\nThere is no unique solution to the matrix.",
print "The final row is empty:\n",A,'<--\n'
return (A,b)