I'm managing a big set of positions at different times, as a sparse matrix: an array of positions (the columns) and an array of times with the same size. E.g.
matrix = numpy.random.randint(2, size = 100).astype(float).reshape(10,10)
times = numpy.nonzero(matrix)[0]+1
positions = numpy.nonzero(matrix)[1]
Now i have to correct the positions with the speeds associated to a time. The problem is that being a sparse matrix, i have to expand the speed associated to a time, to every position at a given time (i.e. to every non-zero element in a given row). I know the indexes of first pisition at agiven time and the number of times nTimes
How can i vectorize this code (i.e. remove the loop)?
indexes = numpy.where(numpy.diff(times)>0)[0]+1
indexes = numpy.concatenate(([0],indexes, [times.size]))
nTimes = numpy.size(indexes)-1
speeds = numpy.random.rand(nTimes)
starts = indexes[:-1]
ends = indexes[1:]
expandedSpeeds = numpy.zeros(positions.size)
for i in numpy.arange(0,nTimes):
expandedSpeeds[starts[i]:ends[i]] = speeds[i]
Edited in order to give a runnable example.
indexes? IfexpandedSpeedshas a first dimension of size 3, that indexing in the last line is a bit weird. On the right hand side of the last line you basically havespeeds[i](except it's inside an array). Could you put a runnable MCVE into your question, please?indexesarray isnumpy.where(numpy.diff(times)>0). I'm gonna write a runnable example.