2

I am trying to create an array which is symmetric with elements placed as below

correct_pic

I have written the following code to get this form with parameter being 0.5 and dimension being 4-by-4.

import numpy as np
a = np.eye(4)
for i in range(4):
    for j in range(4):
        a[i, j] = (0.5) ** (np.abs(i-j))

This does what I need but for large dimension (1000s) this causes a lot of overhead. Is there any other low complexity method to get this matrix? Thanks.

learner
  • 3,168
  • 3
  • 18
  • 35

1 Answers1

3

We can leverage broadcasting after creating a ranged array to represent the iterator variable and then performing an outer-subtraction to simulate i-j part -

n = 4
p = 0.5
I = np.arange(n)
out = p ** (np.abs(I[:,None]-I))

Optimization #1

We can do a hashing based one with indexing, so that we optimize on expensive power computations, like so -

out = (p**np.arange(n))[(np.abs(I[:,None]-I))]

Optimization #2

We can optimize further to use multi-cores with numexpr -

import numexpr as ne

out = ne.evaluate('p**abs(I2D-I)',{'I2D':I[:,None],'I':I})
Divakar
  • 218,885
  • 19
  • 262
  • 358