Question

So I have an array of 500,000 elements:

float* arrayToBucketize=(float*) malloc(sizeof(float)*500000);

and an array that represents the buckets:

int buckets[5]={0,25,50,75,100};

What is the fastest way to go through the first array, look at each float value, compare it to the "buckets" array and replace that float value with the nearest bucket value. So if the float value was 11.25, it would be replaced with 0. On the other hand, 90.10 would be replaced with 100.

Also, I would need any values outside of that range (<0 and >100) to remain unchanged.

I know I can do this with for loops and if conditions; but in the bad habit of optimizing, I am trying to find a more efficient (faster) way of doing this. I am hoping that there is a C function(s) or an iOS function in the Accelerate framework that can do this. Or possibly a series of Accelerate framework matrix functions.

Thanks

Was it helpful?

Solution

For each value inside the bucket range, divide by the lowest common multiple of your bucket values. Round the results to the nearest integer, and then multiply again by the lowest common multiple.

Using the example numbers:

11.25 / 25 = 0.45
0.45 -> 0
0 * 25 = 0

90.10 / 25 = 3.604
3.604 -> 4
4 * 25 = 100

The accelerate framework has vectorized divide, round, and multiply functions, so these should run fairly quickly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top