Create a matrix using a certain vector in Python
Question:
I have this vector m = [1,0.8,0.6,0.4,0.2,0]
and I have to create the following matrix in Python:
I create a matrix of zeros and a double
mm = np.zeros((6, 6))
for j in list(range(0,6,1)):
for i in list(range(0,6,1)):
ind = abs(i-j)
m[j,i] = mm[ind]
But, I got the following output:
array([[1. , 0.8, 0.6, 0.4, 0.2, 0. ],
[0.8, 1. , 0.8, 0.6, 0.4, 0.2],
[0.6, 0.8, 1. , 0.8, 0.6, 0.4],
[0.4, 0.6, 0.8, 1. , 0.8, 0.6],
[0.2, 0.4, 0.6, 0.8, 1. , 0.8],
[0. , 0.2, 0.4, 0.6, 0.8, 1. ]])
That is what I wanted! Thanks anyway.
Answers:
This could be written by comprehension if you do not want to use numpy,
[m[i::-1] + m[1:len(m)-i] for i in range(len(m))]
Here is a way to implement what you want with only numpy functions, without loops (m
is your numpy array):
x = np.tile(np.hstack([np.flip(m[1:]), m]), (m.size, 1))
rows, column_indices = np.ogrid[:x.shape[0], :x.shape[1]]
column_indices = column_indices - np.arange(m.size)[:, np.newaxis]
result = x[rows, column_indices][:, -m.size:]
Example:
>>> result
array([[1. , 0.8, 0.6, 0.4, 0.2, 0. ],
[0.8, 1. , 0.8, 0.6, 0.4, 0.2],
[0.6, 0.8, 1. , 0.8, 0.6, 0.4],
[0.4, 0.6, 0.8, 1. , 0.8, 0.6],
[0.2, 0.4, 0.6, 0.8, 1. , 0.8],
[0. , 0.2, 0.4, 0.6, 0.8, 1. ]])
This approach is much faster than using a list comprehension when m
is large.
I have this vector m = [1,0.8,0.6,0.4,0.2,0]
and I have to create the following matrix in Python:
I create a matrix of zeros and a double
mm = np.zeros((6, 6))
for j in list(range(0,6,1)):
for i in list(range(0,6,1)):
ind = abs(i-j)
m[j,i] = mm[ind]
But, I got the following output:
array([[1. , 0.8, 0.6, 0.4, 0.2, 0. ],
[0.8, 1. , 0.8, 0.6, 0.4, 0.2],
[0.6, 0.8, 1. , 0.8, 0.6, 0.4],
[0.4, 0.6, 0.8, 1. , 0.8, 0.6],
[0.2, 0.4, 0.6, 0.8, 1. , 0.8],
[0. , 0.2, 0.4, 0.6, 0.8, 1. ]])
That is what I wanted! Thanks anyway.
This could be written by comprehension if you do not want to use numpy,
[m[i::-1] + m[1:len(m)-i] for i in range(len(m))]
Here is a way to implement what you want with only numpy functions, without loops (m
is your numpy array):
x = np.tile(np.hstack([np.flip(m[1:]), m]), (m.size, 1))
rows, column_indices = np.ogrid[:x.shape[0], :x.shape[1]]
column_indices = column_indices - np.arange(m.size)[:, np.newaxis]
result = x[rows, column_indices][:, -m.size:]
Example:
>>> result
array([[1. , 0.8, 0.6, 0.4, 0.2, 0. ],
[0.8, 1. , 0.8, 0.6, 0.4, 0.2],
[0.6, 0.8, 1. , 0.8, 0.6, 0.4],
[0.4, 0.6, 0.8, 1. , 0.8, 0.6],
[0.2, 0.4, 0.6, 0.8, 1. , 0.8],
[0. , 0.2, 0.4, 0.6, 0.8, 1. ]])
This approach is much faster than using a list comprehension when m
is large.