Home > Net >  the issues of appending arrays generated in the loop with initial empty array
the issues of appending arrays generated in the loop with initial empty array

Time:04-28

I have the following code, aiming to concatenate arrays generated within a loop, and initiate an empty array before entering the loop. For illustration purposes, i just make loop have one iteration only. However, I found that the result_array still include the initial empty array. I am not clear how to fix this issue, is that possible to append the arrays generated within a loop without setting up initial empty array? For reproducing the problem, am including both code and screenshot of running.

import numpy as np
import hdmedians as hd
x = np.random.rand(5,10,2)
result_array = np.empty((1,2),float)
for i in range(1):#x.shape[1]):
    print('i----',i)
    x1 = x[:,i,:]
    print(x1)
    x2 = hd.medoid(x1,axis=0)    
    x2 = x2.reshape((1,2))
    print(x2)
    print('---------')
    result_array = np.append(result_array, x2, axis =0 )

enter image description here

CodePudding user response:

I don't know the API of hdmedians, so I can't really suggest a vectorial code (if possible), but you can replace your append in a loop (that is inefficient) with:

np.vstack([hd.medoid(x[:,i,:], axis=0)
           for i in range(x.shape[1])])

Output:

array([[0.3595079 , 0.43703195],
       [0.60276338, 0.54488318],
       [0.4236548 , 0.64589411],
       [0.52324805, 0.09394051],
       [0.52184832, 0.41466194],
       [0.57019677, 0.43860151],
       [0.45615033, 0.56843395],
       [0.20887676, 0.16130952],
       [0.65310833, 0.2532916 ],
       [0.46631077, 0.24442559]])
  • Related