Hello (excuse my English), I have a big doubt in python with matrix multiplication, I create a list of lists and multiplied by a scaling matrix, this is what I've done and I can not alparecer perform a multiplication operation problem with indexes, I check with paper and pencil and it works, I'm doing something bad to accommodate indexes or am I wrong accommodating matrices from the beginning?
def main():
if len(sys.argv) > 1:
v = int(sys.argv[1])
else:
print "error python exe:"
print "\tpython <programa.py> <num_vertices>"
A = []
for i in range(v):
A.append([0]*2)
for i in range(v):
for j in range(2):
A[i][j] = input("v: ")
print A
Escala(A)
def Escala(A):
print "Escala"
sx = input("Sx: ")
sy = input("Sy: ")
S = [(sx,0),(0,sy)]
print S
M = mult(S,A)
print M
def mult(m1,m2):
M = zero(len(m1),len(m2[0]))
for i in range(len(m2)):
for j in range(len(m2[0])):
for k in range(len(m1)):
M[i][j] += m1[k][j]*m2[k][j]
print M
return M
def zero(m,n):
# Create zero matrix
new_matrix = [[0 for row in range(n)] for col in range(m)]
return new_matrix
This seems wrong to me:
M[i][j] += m1[k][j]*m2[k][j]
shouldn't it be:
M[i][j] += m1[i][k]*m2[k][j]
Related
I'm trying to make a spiral matrix, but when I tried to make the numbers appear one by one, it only shows the lines one by one.
Please help!
import numpy as np
from time import sleep
n = int(input("Width : "))
k = int(input("Space : "))
a = np.zeros((n,n))
print(a/n)
i = 0 #i line
j = 0 #j column
it = -1 #it upper line
id = n #id downer line
jt = -1 #jt left column
jp = n #jp right column
x = k #x starter number
while j < jp:
while j < jp:
a[i][j] = x
x += k
j +=1
it +=1
i=it+1
j=jp-1
while i< id:
a[i][j] = x
x += k
i +=1
jp -=1
j=jp-1
i=id-1
while j > jt:
a[i][j] = x
x += k
j -=1
id -=1
i=id-1
j=jt+1
while i>it:
a[i][j] = x
x += k
i -=1
jt +=1
i=it+1
j=jt+1
for x in a:
print(x)
sleep(0.1)
Here's an example:
Each number is suppose to appear one by one.
(I'm just putting this here so I can post this since I need to add more details)
Not quite trivial.
I found a solution using an empty character array and cursor-manipulation.
This should result in the desired output:
# replace your last "for x in a" loop by the following
def print_array(arr, block_size=4):
"""
prints a 2-D numpy array in a nicer format
"""
for a in arr:
for elem in a:
print(elem.rjust(block_size), end="")
print(end="\n")
# empty matrix which gets filled with rising numbers
matrix_to_be_filled = np.chararray(a.shape, itemsize=3, unicode=True)
for _ in range(a.size):
# find position of minimum
row, col = np.unravel_index(a.argmin(), a.shape)
# add minimum at correct position
matrix_to_be_filled[row, col] = f'{a.min():.0f}'
# write partially filled matrix
print_array(matrix_to_be_filled)
# delete old minimum in a-matrix
a[row, col] = a.max()+1
sleep(0.1)
# bring cursor back up except for last element
if _ < a.size-1:
print('\033[F'*(matrix_to_be_filled.shape[0]+1))
If you are using pycharm, you need to edit the run/debug configuration and active "emulate terminal in output console" to make the special "move up" character work
I am trying to recursively generate Hadamard matrices by Sylvester construction, following this recurrence formula:
H(2) = (1 1)
(1 -1)
H(2**k) = ( H(2**(k-1)) H(2**(k-1)) )
( H(2**(k-1)) -H(2**(k-1)) )
this formula as an image of LaTeX
Or using the notation (x) for Kronecker product:
H(2**k) = H(2) (x) H(2**(k-1))
My code to generate a Hadamard matrix by Sylvester construction is as follows:
def deepMap(f,seq):
if seq == []:
return seq
elif type(seq) != list:
return f(seq)
else:
return [deepMap(f,seq[0])] + deepMap(f,seq[1:])
def Hadamard(n): #n is a power of 2
if n == 1:
return [1]
elif n == 2:
return [[1,1],[1,-1]]
else:
k = 2
array = [Hadamard(k)]
while k < n:
k *= 2
matrix,prev = [],array.pop(0)
for i in range(k):
if i < k//2:
matrix.append(prev[i]+prev[i])
else:
matrix.append(prev[i%(k//2)]+deepMap(lambda x: -x,prev[i%(k//2)]))
array.append(matrix)
#print(f'matrix {k} = {matrix}')
return array[0]
The code works, but is pretty slow, and exceeds maximum depth recursion when n > 1024.
How could I make the code handle larger values of n?
Context: This code was written for a Kattis question https://open.kattis.com/problems/sylvester
Fixing your code: recursion in deepMap
With just a small modification to your deepMap function, it becomes faster and avoids stacking up thousands of recursive calls: replace return [deepMap(f,seq[0])] + deepMap(f,seq[1:]) with return [deepMap(f, x) for x in seq].
def deepMap(f,seq):
if seq == []:
return seq
elif type(seq) != list:
return f(seq)
else:
return [deepMap(f, x) for x in seq]
def Hadamard(n): #n is a power of 2
if n == 1:
return [1]
elif n == 2:
return [[1,1],[1,-1]]
else:
k = 2
array = [Hadamard(k)]
while k < n:
k *= 2
matrix,prev = [],array.pop(0)
for i in range(k):
if i < k//2:
matrix.append(prev[i]+prev[i])
else:
matrix.append(prev[i%(k//2)]+deepMap(lambda x: -x,prev[i%(k//2)]))
array.append(matrix)
#print(f'matrix {k} = {matrix}')
return array[0]
print( Hadamard(2048) ) # should take less than a second
A different version: avoiding .append
Since we already know the size of the matrix, I suggest creating a matrix that already has the correct size, then filling it recursively or iteratively. To fill the matrix, I made a function dup that duplicates a quadrant of the matrix to another quadrant.
def dup(h, k, i0,j0, s=1):
for i in range(k):
for j in range(k):
h[i0+i][j0+j] = s * h[i][j]
def had(n):
'''assume n >= 2 is a power of 2'''
h = [[0 for _ in range(n)] for _ in range(n)]
h[0][0]=1
h[0][1]=1
h[1][0]=1
h[1][1]=-1
k = 2
while k < n:
dup(h, k, 0,k)
dup(h, k, k,0)
dup(h, k, k,k, -1)
k *= 2
return h
print( had(2048) )
Using numpy: everything is easy with concatenate
Using numpy.concatenate, the code becomes much shorter, much much faster, and easier to read:
from numpy import array, concatenate
def hadamard(n):
'''assume n is a power of 2'''
if n == 1:
return array([1])
elif n == 2:
return array([[1,1],[1,-1]])
else:
a = hadamard(n // 2)
return concatenate(
(concatenate((a, a), axis=1),
concatenate((a, -a), axis=1)),
axis=0
)
print( hadamard(2048) )
I'm really new at Python so I apologize in advance if this is a really dumb question. Pretty much, I'm writing a longest common subsequence algorithm with dynamic programming.
Whenever I try to run it, I get the IndexError: list index out of range, and I don't know why because the array I'm adding values to never changes in size. Code snippet for clarity:
def LCS(sequence1, sequence2):
n = len(sequence1)
m = len(sequence2)
D = [[0 for num in range(0,n)]for number in range(0, m)]
for i in range(1, n):
for j in range(1, m):
if(sequence1[i] == sequence2[j]):
D[i][j] = D[i-1][j-1] + 1
else:
D[i][j] = max(D[i-1][j], D[i][j-1])
print D[n][m]
There seem to be two problems:
In the definition of D, you should swap n and m
D = [[0 for num in range(0, m)] for number in range(0, n)]
You have to print (or better: return) the last element of the matrix
return D[n-1][m-1] # or just D[-1][-1]
The issue is with total rows and columns of the matrix(D). Size should be (m+1)*(n+1) and then loop over the matrix. Otherwise you need to return D[m-1][n-1].
def LCS(sequence1, sequence2):
n = len(sequence1)
m = len(sequence2)
D = [[0 for num in range(0,n+1)]for number in range(0, m+1)]
for i in range(1, n+1):
for j in range(1, m+1):
if(sequence1[i-1] == sequence2[j-1]):
D[i][j] = D[i-1][j-1] + 1
else:
D[i][j] = max(D[i-1][j], D[i][j-1])
print D[n][m]
LCS('abcdef' , 'defjkl')
I wrote this code for dynamic programming implementation of the knapsack problem.
#B = maximum weight
#n = number of items
#p = list of weights
#a = list of values
#p[i] = weight with value a[i]
def maximum_attractiveness(n, B, p, a):
f = [i for i in range(n+1)]
m = [f for i in range(B+1)]
m[0] = [0 for i in range(len(m[0]))]
for i in m:
i[0] = 0
print(m)
for j in range(n):
for w in range(B):
if (p[j]) > (w):
m[w][j] = m[w][j-1]
else:
m[w][j] = max(m[w][j-1],m[w-p[j]][j-1]+a[j])
return m[B][n]
I get an incorrect output for this algorithm. where did I go wrong?
f = [i for i in range(n+1)]
m = [f for i in range(B+1)]
This uses the same array f for every position m, so for example if you change m[1][k], you also change m[i][k] for every i. You probably meant to do
m = [[i for i in range(n+1)] for i in range(B+1)]
There might be some other bugs I think, so maybe you should print out the intermediate arrays at some points to check out where the results are not what you'd expect them to be.
UPDATE:
Your initialization seems strange to me. I think it should be just m = [[0]*n for i in range(B+1)] because you need a matrix of zeroes.
it should be for w in range(B+1)
you should not return m[B][n], but max(m[j][n] for j in range(B+1)).
My attempt, which avoids the the matrix altogether and only uses a single array:
m = [0]*(B+1)
for j in range(n):
for w in range(B,p[j]-1,-1):
m[w] = max(m[w], m[w-p[j]] + a[j])
return max(m)
I'm about to write some code that computes the determinant of a square matrix (nxn), using the Laplace algorithm (Meaning recursive algorithm) as written Wikipedia's Laplace Expansion.
I already have the class Matrix, which includes init, setitem, getitem, repr and all the things I need to compute the determinant (including minor(i,j)).
So I've tried the code below:
def determinant(self,i=0) # i can be any of the matrix's rows
assert isinstance(self,Matrix)
n,m = self.dim() # Q.dim() returns the size of the matrix Q
assert n == m
if (n,m) == (1,1):
return self[0,0]
det = 0
for j in range(n):
det += ((-1)**(i+j))*(self[i,j])*((self.minor(i,j)).determinant())
return det
As expected, in every recursive call, self turns into an appropriate minor. But when coming back from the recursive call, it doesn't change back to it's original matrix.
This causes trouble when in the for loop (when the function arrives at (n,m)==(1,1), this one value of the matrix is returned, but in the for loop, self is still a 1x1 matrix - why?)
Are you sure that your minor returns the a new object and not a reference to your original matrix object? I used your exact determinant method and implemented a minor method for your class, and it works fine for me.
Below is a quick/dirty implementation of your matrix class, since I don't have your implementation. For brevity I have chosen to implement it for square matrices only, which in this case shouldn't matter as we are dealing with determinants. Pay attention to det method, that is the same as yours, and minor method (the rest of the methods are there to facilitate the implementation and testing):
class matrix:
def __init__(self, n):
self.data = [0.0 for i in range(n*n)]
self.dim = n
#classmethod
def rand(self, n):
import random
a = matrix(n)
for i in range(n):
for j in range(n):
a[i,j] = random.random()
return a
#classmethod
def eye(self, n):
a = matrix(n)
for i in range(n):
a[i,i] = 1.0
return a
def __repr__(self):
n = self.dim
for i in range(n):
print str(self.data[i*n: i*n+n])
return ''
def __getitem__(self,(i,j)):
assert i < self.dim and j < self.dim
return self.data[self.dim*i + j]
def __setitem__(self, (i, j), val):
assert i < self.dim and j < self.dim
self.data[self.dim*i + j] = float(val)
#
def minor(self, i,j):
n = self.dim
assert i < n and j < n
a = matrix(self.dim-1)
for k in range(n):
for l in range(n):
if k == i or l == j: continue
if k < i:
K = k
else:
K = k-1
if l < j:
L = l
else:
L = l-1
a[K,L] = self[k,l]
return a
def det(self, i=0):
n = self.dim
if n == 1:
return self[0,0]
d = 0
for j in range(n):
d += ((-1)**(i+j))*(self[i,j])*((self.minor(i,j)).det())
return d
def __mul__(self, v):
n = self.dim
a = matrix(n)
for i in range(n):
for j in range(n):
a[i,j] = v * self[i,j]
return a
__rmul__ = __mul__
Now for testing
import numpy as np
a = matrix(3)
# same matrix from the Wikipedia page
a[0,0] = 1
a[0,1] = 2
a[0,2] = 3
a[1,0] = 4
a[1,1] = 5
a[1,2] = 6
a[2,0] = 7
a[2,1] = 8
a[2,2] = 9
a.det() # returns 0.0
# trying with numpy the same matrix
A = np.array(a.data).reshape([3,3])
print np.linalg.det(A) # returns -9.51619735393e-16
The residual in case of numpy is because it calculates the determinant through (Gaussian) elimination method rather than the Laplace expansion. You can also compare the results on random matrices to see that the difference between your determinant function and numpy's doesn't grow beyond float precision:
import numpy as np
a = 10*matrix.rand(4)
A = np.array( a.data ).reshape([4,4])
print (np.linalg.det(A) - a.det())/a.det() # varies between zero and 1e-14
use Sarrus' Rule (non recursive method)
example on below link is in Javascript, but easily can be written in python
https://github.com/apanasara/Faster_nxn_Determinant
import numpy as np
def smaller_matrix(original_matrix,row, column):
for ii in range(len(original_matrix)):
new_matrix=np.delete(original_matrix,ii,0)
new_matrix=np.delete(new_matrix,column,1)
return new_matrix
def determinant(matrix):
"""Returns a determinant of a matrix by recursive method."""
(r,c) = matrix.shape
if r != c:
print("Error!Not a square matrix!")
return None
elif r==2:
simple_determinant = matrix[0][0]*matrix[1][1]-matrix[0][1]*matrix[1][0]
return simple_determinant
else:
answer=0
for j in range(r):
cofactor = (-1)**(0+j) * matrix[0][j] * determinant(smaller_matrix(matrix, 0, j))
answer+= cofactor
return answer
#test the function
#Only works for numpy.array input
np.random.seed(1)
matrix=np.random.rand(5,5)
determinant(matrix)
Here's the function in python 3.
Note: I used a one-dimensional list to house the matrix and the size array is the amount of rows or columns in the square array. It uses a recursive algorithm to find the determinant.
def solve(matrix,size):
c = []
d = 0
print_matrix(matrix,size)
if size == 0:
for i in range(len(matrix)):
d = d + matrix[i]
return d
elif len(matrix) == 4:
c = (matrix[0] * matrix[3]) - (matrix[1] * matrix[2])
print(c)
return c
else:
for j in range(size):
new_matrix = []
for i in range(size*size):
if i % size != j and i > = size:
new_matrix.append(matrix[i])
c.append(solve(new_matrix,size-1) * matrix[j] * ((-1)**(j+2)))
d = solve(c,0)
return d
i posted this code because i couldn't fine it on the internet, how to solve n*n determinant using only standard library.
the purpose is to share it with those who will find it useful.
i started by calculating the submatrix Ai related to a(0,i).
and i used recursive determinant to make it short.
def submatrix(M, c):
B = [[1] * len(M) for i in range(len(M))]
for l in range(len(M)):
for k in range(len(M)):
B[l][k] = M[l][k]
B.pop(0)
for i in range(len(B)):
B[i].pop(c)
return B
def det(M):
X = 0
if len(M) != len(M[0]):
print('matrice non carrée')
else:
if len(M) <= 2:
return M[0][0] * M[1][1] - M[0][1] * M[1][0]
else:
for i in range(len(M)):
X = X + ((-1) ** (i)) * M[0][i] * det(submatrix(M, i))
return X
sorry for not commenting before guys :)
if you need any further explanation don't hesitate to ask .