0

I have three arrays of shapes:

A = a = np.random.exponential(1, [10, 1000000])  # of shape (10, 1000000)
B = a = np.random.exponential(1, [10, 1000000])  # of shape (10, 1000000)

I computed another array IND[ ] as below. Each element of IND[ ] is index of the maximum element of A (maximum of each 10 values in a column) ,

IND = np.argmax(snr_sr, axis=0)  # of shape (1000000,)

I want to calculate another array C, which contains the element-wise minimum values of A and B at row# specified by values of IND[ ]. Thus the C array should be of the shape (1, 1000000). I want to avoid for loops. I tried the below, but the values of C are not correct.

for j in range(0, A.shape[1]):    
        m  = ind[j]
        C  = minimum(A[m,:], B[m,:])  # return 1x1000000 array

Sorry, as the arrays are large, could not post it. You can take any arrays of the same shapes.

First Edit: Somebody provided me with the right answer, but he deleted it (don't know why?) Anyhow, I copied the answer before he deleted it. Please post it again so that I can mark it correct. (To him: Who took arrays of 1,100 for simplicity).

2 Answers2

1

I shortened your arrays:

a = np.random.exponential(1, [10, 100])  # of shape (10, 100)
b = np.random.exponential(1, [10, 100])
ind=np.argmax(a,axis=0)

Use that ind to select one row per column in a and b:

a_ = a[ind,np.arange(a.shape[1])]
b_ = b[ind,np.arange(a.shape[1])]

And then calculate c:

c=np.minimum(a_, b_)
Brenlla
  • 1,471
  • 1
  • 11
  • 23
  • Thanks. It's beautifully solved. What if the "ind" is a random selection on axis=0 instead of maximum?? – Muhammad Asif Khan Jul 08 '18 at 13:25
  • It should be the same, if `ind` >9 it will throw an indexing error though – Brenlla Jul 08 '18 at 13:29
  • No, I mean if I want the index of randomly selected elements of the two arrays instead of ind = np.argmax(a, axis=0), just for example, ind=np.argrandom(a, axis=0) (np.argrandom doe not exist, I am just curious if such a function exist?) – Muhammad Asif Khan Jul 08 '18 at 13:31
  • Calculate random `ind`? Use the `random` module: `ind=np.random.randint(0,10,a.shape[0])` – Brenlla Jul 08 '18 at 13:38
  • I think it works. Let me verify it by seeing the final results. Thank you so much Brenlla. You were really helpful. – Muhammad Asif Khan Jul 08 '18 at 13:48
0

Note: I am not proficient in numpy, so there might be more efficient solutions.

First find the minimum of values in A and B row-wise:

minAB = np.min(np.minimum(A, B), axis=1)

Then index this array using ind:

C = minAB[ind]
today
  • 32,602
  • 8
  • 95
  • 115