I just asked this question over Stack Over Flow on how to improve my code and reposting it here as someone on Stack Overflow recommended this platform.
I have written two python functions and they are correct, but I believe this is not the efficient way to write them, and I am wondering if some can give their input on how to improve them.
The first function is the following which generates an odd number of weights that sum up to one.
import numpy as np
# the argument of the following function has to an non-negative and odd
# integer
def weights(n_w):
M = int((n_w+1)/2)
j = np.arange(-M+1, M,1)
w = 2.**(-j**2)
w = w/w.sum()
return w
If I now type
weights(5)
I get five weights, which add up to 1.
Out[442]: array([0.02941176, 0.23529412, 0.47058824, 0.23529412, 0.02941176])
The first and last entry of the output array is the same and similarly second and the fourth are also the same.
So, I can generate any odd number of normalized weights using the function above.
I have used this function to write the following function which generates an n by n square matrix with each row having an odd number of weights and zeros.
def weight_matrix(n_w,n):
w_matrix = np.zeros((n,n))
M = int((n_w+1)/2)
W_main = weights(n_w)
for m in range(1,M-1):
w = weights(2*m+1)
w_matrix[m,:int(len(w))] = w
w_matrix += w_matrix[::-1,::-1]
w_matrix[0,0], w_matrix[-1,-1] = [1,1]
nn = 0
for m in range(M-1,n-M+1):
w = W_main
w_matrix[m,nn:nn+n_w] = w
nn += 1
return w_matrix
An example of this function is
weight_matrix(5,7)
where the second argument specifies the dimension of the output matrix and the first argument decides the maximum number weights to be generated.
Following is the output:
array([[1. , 0. , 0. , 0. , 0. ,
0. , 0. ],
[0.25 , 0.5 , 0.25 , 0. , 0. ,
0. , 0. ],
[0.02941176, 0.23529412, 0.47058824, 0.23529412, 0.02941176,
0. , 0. ],
[0. , 0.02941176, 0.23529412, 0.47058824, 0.23529412,
0.02941176, 0. ],
[0. , 0. , 0.02941176, 0.23529412, 0.47058824,
0.23529412, 0.02941176],
[0. , 0. , 0. , 0. , 0.25 ,
0.5 , 0.25 ],
[0. , 0. , 0. , 0. , 0. ,
0. , 1. ]])
Each row adds up to 1
The first element of the first row is 1 which is the only non-zero element of it.
Similarly, the last element of the last row is 1 which is the only non-zero element of it.
The second row and the second to the last have the same three non-zero elements but at different positions.
From row 3 to the last row have the same five non-zero elements but at different positions.
These five non-zero elements shift along the diagonal of the matrix.
The second function gives me control over what size matrix to generate and how long I shall increase the number of weights.
Any suggestion to improve these functions will be appreciated.