Phorce
Phorce

Reputation: 4642

Mean Average vector from 1D vector transposed

This has been annoying me for most of the day..

Suppose that I have the following vector:

v = [1, 2, 4, 9]

I transpose this, so the vector is in columns:

v = [1, 2
    4, 9]

I do this, using the following method:

for(unsigned i=0; (i < cols); i++)
{
    for(unsigned j=0; (j < 2); j++)
    {
         std::cout << vect[i*2+j] << " ";
    }
    std::cout << std::endl;
}

But how would I calculate the columns, first? My aim is to achieve the following:

(1 + 4)/2 = 2.5
(2 + 9)/2 = 5.5

Therefore, a resulting vector would return the mean matrix: x = [2.5, 5.5]

I have tried the following:

double summation = 0;

for(unsigned i=0; (i < cols); i++)
    {
        for(unsigned j=0; (j < size); j++)
        {
            summation += values[i*(i*j)+j];
        }
        std::cout << summation << std::endl;
    }

Which produces: 3 8

I am probably missing something really stupid here, but, I can't seem to figure out what.

I have also tried to have a variable subRow which begins at 0 and increments each time by 3 but this did not work either.

Upvotes: 0

Views: 104

Answers (3)

Kiwi
Kiwi

Reputation: 2816

int v[] = {1,2,4,9};
int cols = 2;
int rows = 2;
for(int c=0 ; c < cols ; c++) {
    double sum=0;
    for(int r=0 ; r < rows ; r++)
        sum += v[cols*r+c];
    std::cout << sum /rows << std::endl;
}

Upvotes: 0

Zac Howland
Zac Howland

Reputation: 15872

You may find it easier to debug if keep your index calculations simple:

std::vector<int> v{1, 2, 4, 9};
const unsigned int WIDTH = 2;
for (unsigned int i = 0; i < WIDTH; ++i)
{
    double sum = 0.0;
    for (unsigned int j = i; j < v.size(); j += WIDTH)
    {
        sum += v[j];
    }
    // do something with sum
}

Your problem appears to be here: for(unsigned j=0; (j < size); j++)

You are starting j at 0 and increment by 1 to size() each time. Most of the values you hit will not be valid for what you are trying to do.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490218

Your last sentence has the right idea, but not quite the right number. Where you mention 3, it appears you need 2. That's normally called the "stride". Using it, averaging by columns would come out something like this:

for (int i=0; i<stride; i++) {
    double total = 0;
    for (int j=0; j<input.size(); j+=stride)
        total += input[j];
    result[i] = total / (j.size()/stride);
}

At least for the moment, this takes for granted that the size of the input matrix really is "correct" --i.e., an even multiple of the stride you specify.

Upvotes: 2

Related Questions