MedicalMath
MedicalMath

Reputation: 1

trouble populating a numpy array

My code below is not populating the numpy/pylab array called RRmeanArray. Can anyone show me how to fix the code so that it populates the array?

    import pylab as p
    RRmeanArray = p.array([])
    startBeatIndex = 0
    endBeatIndex = 10
    for k in range(int(p.floor(len(QRSandRRarray[0])/10))-1):
        print '++++++++++++++++++++++++++++++++++++++++++++'
        print 'k is:  ',k
        print 'startBeatIndex is:  ',startBeatIndex
        print 'endBeatIndex is:  ',endBeatIndex
        print 'p.mean(QRSandRRarray[1,startBeatIndex:endBeatIndex]) is:  ',p.mean(QRSandRRarray[1,startBeatIndex:endBeatIndex])
        newMean = p.mean(QRSandRRarray[1,startBeatIndex:endBeatIndex])
        print 'newMean is:  ',newMean
        RRmeanArray += [newMean]
        print 'len(RRmeanArray) is:  ',len(RRmeanArray)
        startBeatIndex += 10
        endBeatIndex += 10
        print '++++++++++++++++++++++++++++++++++++++++++++'

Here is what I am getting as output in the python shell for a typical iteration of k:

++++++++++++++++++++++++++++++++++++++++++++
k is:   619
startBeatIndex is:   6190
endBeatIndex is:   6200
p.mean(QRSandRRarray[1,startBeatIndex:endBeatIndex]) is:   0.5971
newMean is:   0.5971
len(RRmeanArray) is:   0
++++++++++++++++++++++++++++++++++++++++++++

EDIT: Thanks, Thomas. You almost got it. The working version is:

    RRmeanArray = p.zeros(len(range(int(p.floor(len(QRSandRRarray[0])/10))-1)))
    startBeatIndex = 0
    endBeatIndex = 10
    for i,k in enumerate(range(int(p.floor(len(QRSandRRarray[0])/10))-1)):
        newMean = p.mean(QRSandRRarray[1,startBeatIndex:endBeatIndex])
        RRmeanArray[i] += [newMean]
        startBeatIndex += 10
        endBeatIndex += 10

This question is now answered.

Upvotes: 0

Views: 345

Answers (1)

Thomas
Thomas

Reputation: 6752

Apparently += operator (which calls the method array.extend) doesn't exist for numpy arrays. If you're using a numpy array, you should preallocate it by making it the full size of what you're going to need.

RRmeanArray = p.zeros(len(range(int(p.floor(len(QRSandRRarray[0])/10))-1)))
for i,k in enumerate(range(int(p.floor(len(QRSandRRarray[0])/10))-1)):
    RRmeanArray[i] = p.mean(QRSandRRarray[1,startBeatIndex:endBeatIndex])
    startBeatIndex += 10
    endBeatIndex += 10

Adding on to the end of the array isn't really what numpy arrays are for - for that you might want a list.

Edit: fixed newMean to be RRmeanArray, what was meant all along. I think this is what you want, not your version where you increment RRmeanArray[i] by [newMean], but I'm glad something's working for you.

Upvotes: 1

Related Questions