-1

I am having a difficulty vectorizing the following for loops in Python.

out = np.zeros((N, d))
dir_int = []

for i in range(N):
    dir_int.append(np.random.randint(low=0, high = d))
    out[i,dir_int[i]] = 1

#where:
# direct_int has shape (N, )
# u has shape (N, d)
# x has the same shape as u
# A has shape (2d, d) = [I,-I]^T, I the dxd identity
# b has shape (2d, )

bmAx = b - np.concatenate((x,-x), axis=1) #This is b-Ax has shape N x 2d
upper = np.copy(x) 
lower = np.copy(x) 

temp = np.zeros(2)
for i in range(len(dir_int)):
    temp[0] = bmAx[i, dir_int[i]]
    temp[1] = -bmAx[i, d + dir_int[i]]
            
    upper[i, dir_int[i]] += np.amax(temp)
    lower[i, dir_int[i]] += np.amin(temp)

For the first loop, dir_int can be created as dir_int = np.random.randint(low=0, high = d, size = N). Then for each "row" of out one of its columns should be 1; this column is dir_int[row]. Not sure how to do that in one line.

The second loop is even harder than the first. Any help is much appreaciated.

Ruzayqat
  • 149
  • 1
  • 1
  • 7
  • 1
    Does this answer your question? [NumPy selecting specific column index per row by using a list of indexes](https://stackoverflow.com/questions/23435782/numpy-selecting-specific-column-index-per-row-by-using-a-list-of-indexes) see [hpaulj's answer](https://stackoverflow.com/a/61234228/843953) – Pranav Hosangadi Feb 16 '23 at 13:12
  • @PranavHosangadi Thanks a lot for the comment. Yes ```np.put_along_axis``` is what I am looking for. – Ruzayqat Feb 16 '23 at 13:20

1 Answers1

0

The first loop comes out as

out = np.zeros((N, d))
dir_int = np.random.randint(0, d, N)
out[np.arange(N), dir_int] = 1

and it it's a bit harder to help with the second one, since b and x are undefined and I'm not sure I'm visualizing the desired output. But you should be able to use dir_int to index into bMax to update an entire N-length column at a time.

AKX
  • 152,115
  • 15
  • 115
  • 172