I am coding a function to create generator matrix using Reed-Solomon encoding in Python. it is currently using for loops but i was wondering if there is a more efficient way to this. My code is:
def ReedSolomon(k,p):
M = np.zeros((k,p))
for i in range(k):
for j in range(p):
M[i][j] = j**i
return M
I believe my function works but may not scale well to large p and k
The generalized equation for an element at index r, c
in your matrix is c**r
.
For a matrix of shape k, p
, you can create two arange
s -- a row vector from 0
to p-1
, and a column vector from 0
to k-1
, and have numpy automatically broadcast the shapes:
def ReedSolomon(k,p):
rr = np.arange(k).reshape((-1, 1))
cc = np.arange(p)
return cc**rr
Calling this function with e.g. k=5, p=3
gives:
>>> ReedSolomon(5, 3)
array([[ 1, 1, 1],
[ 0, 1, 2],
[ 0, 1, 4],
[ 0, 1, 8],
[ 0, 1, 16]])