0

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.

2
  • What did you try so far? You could use a for loop and some modulo indexing. Commented Nov 22, 2022 at 10:52
  • your output seems to match what you want. So what's your question? Commented Nov 22, 2022 at 11:12

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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))]

1 Comment

you are welcome, you could as well vote up if this answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.