0

I have a set of values stored in a 2d matrix. I want to create separate totals for the values which have the same first index. Here's a short example:

typedef int matrix [9][9];
matrix sampleMatrix;

sampleMatrix [1][2] = 3;
sampleMatrix [1][4] = 5;
sampleMatrix [3][5] = 6;
sampleMatrix [3][2] = 2;
sampleMatrix [5][1] = 1;

for (int i = 0; i < 9; i++){
   for (int j = 0; j < 9; j++){
        //here's where I'm stuck
        //if i = 1, then total all values with i = 1 etc.
        if(sampleMatrix[i]){ 
        int sum = sum + sampleMatrix[i][j];
        }
        std::cout << i << " Total: " << sum << std::endl;
   }

}

Thanks for any help.

2 Answers 2

1

If you initialize all values of array with 0 then you would be able to sum up all values of each i'th index

matrix sampleMatrix;
for(int i=0;i<9;i++){
    for(int j=0;j<9;j++){
         sampleMatrix[i][j]=0;
    }
}

sampleMatrix [1][2] = 3;
sampleMatrix [1][4] = 5;
sampleMatrix [3][5] = 6;
sampleMatrix [3][2] = 2;
sampleMatrix [5][1] = 1;

for (int i = 0; i < 9; i++){
   int sum=0;
   for (int j = 0; j < 9; j++){
          sum = sum + sampleMatrix[i][j];       
   }
   cout<<sum<<endl;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Build a integer array of the length 9 like int sums [9] and initialize each entry with 0. In your double for loop, for every sampleMatrix [i][j] entry, add it to the corresponding entry of the sums array, like sums [i] += sampleMatrix [i][j]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.