Storage of the sum of matrices in vector

1

This function that I created needs to calculate the sum of each column of the array and store it in a vector position. However, it is not giving the desired result, I think it can be within the third% of%.

Can anyone help me with regard to saving the result of the sum of the array in the vector?

void soma(int mat[] [MAX], int n, int m, int v[])  
{

int i,j,soma=0;
int res, x=0;


for (i = 0; i < n; i ++)
{
    for ( j = 0; j < m ;j ++)
    { 
        for(x=0; x < m; x++)
        {
            soma=soma+ mat[i][j];
            res[v]=soma;
            printf(" %d\n",res );
        }
    }
}



}  
    
asked by anonymous 18.06.2018 / 20:19

2 answers

1

You run through the array in two dimensions, row and column, so it only makes sense to have two for s.

The vector where you save the result is traversed along with the column, containing the sum of the values in each row, so it makes sense to go through the columns first and then the rows.

In its implementation, the variable soma is accumulating the values of all elements of the array, not accumulating them by column. Also, since there is a third for , each value will be counted m times.

I think instead of res[v] , you'd better use v[res] . In fact, the variable res does not have its value set anywhere, so it would be v[alguma_outra_coisa] .

What you wanted was this:

void soma(int mat[][MAX], int n, int m, int v[]) {
    for (int j = 0; j < m; j++) {
        v[j] = 0;
        for (int i = 0; i < n; i++) { 
            v[j] += mat[i][j];
        }
    }
}
    
18.06.2018 / 22:45
0

I looked for storage of array sums in vectors and found the GUJ site.

for(i = 0; i < 4; i++) {
   for(j = 0; j < 5; j++ {
       vetorA[j] += matriz[i][j];
       vetorB[i] += matriz[i][j];

Source: link

  

Note: I did not format the code, I just took the logical part of the response from a problem where someone wanted to store the values of the   same way as you. Read more on the site via the   doubts.

    
18.06.2018 / 20:27