Array sum storage in vector

Asked

Viewed 392 times

1

This function I created needs to calculate the summing up of each column of the matrix and store in a vector position. However, it is not giving the desired result, I think it may be within the thirdfor.

Can anyone help me in relation to saving the result of the sum of the matrix 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 );
        }
    }
}



}  

2 answers

1


You walk through the matrix in two dimensions, row and column, so it only makes sense to have two fors.

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

In its implementation, the variable soma is accumulating the values of all matrix elements, not accumulating them per column. Also, as there is a third for, each value shall be accounted for m times.

I guess instead of res[v], you’d better use v[res]. In fact, the variable res doesn’t have its defined value 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];
        }
    }
}

0

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

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

Source: http://www.guj.com.br/t/armazenar-soma-de-linhas-de-matriz-em-vetor/361757

Observing: I didn’t format the code, I just took the logical part of the answer to a problem where someone wanted to store the values of the same way as you. Read more on the site via doubts.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.