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:

enter image description here

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.

Asked By: MacUser

||

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))]
Answered By: amirhm

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.

Answered By: Riccardo Bucco
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.