Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I average a subset of an array and store the result in another array?

I have a C array fftArray[64] that contains values that I want averaged and placed into another array frequencyBar[8]. Getting the average of the entire array would be easy enough using a for statement.

int average, sum = 0;
for (i = 0; i < 64; i++)
{
     sum += fftArray[i];
}
average = sum/64;

But I just can't seem to figure out how to get the average from fftArray[0] through fftArray[8] and store this in frequencyBar[0], the average of fftArray[9] through fftArray[16] and store this in frequencyBar[1], etc. Can anyone help me out with this? Thanks

like image 899
K. Barresi Avatar asked Feb 23 '23 16:02

K. Barresi


2 Answers

This looks like a homework assignment, so, rather than give you the outright answer, I'd rather just point you in the right direction...

use a nested loop (one inside the other). One loop cycles 0-7, the other one 0 - 63. Use the smaller one to populate your sliced averages.

or better yet use the % operator to see when you've gone through 8 elements and do an average of your total, then reset the total for the next set. Then you'll have learned how to use the % operator too! :)

[EDIT] ok, if not homework then something like this... I haven't written C in 5 years, so treat this as pseudo code:

//assuming you have a fftArray[64] with data, as per your question
int i,sum,avCounter,total;
int averages[8]; 
for(i=0 , avCounter=0, total=0 ; i<64; ){
    total += fftArray[i];
    if(++i % 8 == 0){   //%gives you the remainder which will be 0 every 8th cycle
      averages[avCounter++] = total / 8
      total = 0;  //reset for next cycle
    }
}

I think this will work better than a nested loop... but I'm not sure since % is division which is more processor heavy than addition... however... I doubt anyone would notice :)

like image 104
Yevgeny Simkin Avatar answered Apr 27 '23 16:04

Yevgeny Simkin


int i, j;
for (i = 0; i < 8; i++) {
    int sum = 0;
    for (j = 0; j < 8; j++) {
        sum += fftArray[ 8*i + j ];
    }
    frequencyBar[i] = sum / 8;
}

Bonus exercise: Optimize this code for speed on your chosen platform.

like image 23
Ilmari Karonen Avatar answered Apr 27 '23 14:04

Ilmari Karonen