views:

75

answers:

2

Hi all,

I'm writing for the iPhone and I'm trying to measure the time between maximum accelerations. Imagine you've attached your iPhone to an oscillating spring. What I want to do is measure the frequency of the oscillation. The way I am going about doing this is storing a certain number acceleration values (updated 20 times per second) in an NSMutableArray and comparing the current acceleration value with previous acceleration values.

How do I add each updated acceleration value to the NSMutableArray and at the same time delete values from the back of the array as I don't need them any more?

Thanks in advance!

+1  A: 

Are NSMutableArrays -addObject:/-insertObject:atIndex: and -removeLastObject/-removeObjectAtIndex: what you're looking for? See this one for more information.

flohei
+1  A: 

Think of the array as a wheel. Once you have filled it up, use a rotating index for the replace location.

myIndex = ( ( myIndex + 1 ) % myCount );
[myArray replaceObjectAtIndex:myIndex withObject:newValue];

You can initialize it with a bunch of [NSNull null] objects that you will replace, so you do not need other special processing the first time through.

Once you have finished collecting data, organize the array to have the appropriate element first if it simplifies other operations.

NSRange range = NSMakeRange( 0 , myIndex );
NSArray *temp = [myArray subarrayWithRange:range];
[myArray removeObjectsInRange:range];
[myArray addObjectsFromArray:temp];
drawnonward
This is a more computationally efficient method than flohei's answer, since the array doesn't have to change in size. The only thing to add is that to initialise `myArray`, you should use `[NSMutableArray arrayWithCapacity:myCount]`, instead of `[NSMutableArray array]`, since you already know the size of the buffer array when you create it.
Nick Forge