user3804161 - 5 months ago 6x

Java Question

I want to find out row sum average but in case zero appears in the row then that particular column should be left when average of the row is done. let it be more clear. i have a matrix say

`5 3 4 4 0`

3 1 2 3 3

4 3 4 3 5

3 3 1 5 4

1 5 5 2 1

row sum average for the first row should be 16/4 instead of 16/5 because we left row 1 column 5 since it contains "0" value

i am trying following code. for the first row its working fine but for the rest each row 2-5 and each column 5 its leaving the value although its not zero.

my code is:

`int rows = 5;`

int cols = 5;

float hostMatrix[] = createExampleMatrix(rows, cols);

System.out.println("Input matrix:");

System.out.println(createString2D(hostMatrix, rows, cols));

float sums[] = new float[rows];

for(int i=0;i<rows;i++){

float sum = 0,counter=0;

for(int j=0;j<cols;j++){

if(hostMatrix[j]==0){

sum += hostMatrix[i * cols + j];

}

else

{

sum += hostMatrix[i * cols + j];

counter++;

}

}

sum=sum/counter;

sums[i] = sum;

}

System.out.println("sums of the columns ");

for(int i=0;i<rows;i++){

System.out.println(" "+sums[i]);

}

output of the program i receive is:

`sums of the columns`

4.0

3.0

4.75

4.0

3.5

i want the output as:

`4.0`

2.4

3.8

3.2

2.8

please guide me where i am doing wrong

Answer

The code below should fix this. The problem was that your inner loop was not iterating correctly. I changed it to index into the right spot in the array. Let me know if it works!

```
int rows = 5;
int cols = 5;
float hostMatrix[] = createExampleMatrix(rows, cols);
System.out.println("Input matrix:");
System.out.println(createString2D(hostMatrix, rows, cols));
float sums[] = new float[rows];
for(int i=0; i<rows; i++){
float sum = 0,counter=0;
for(int j=0; j<cols; j++){
//the problem was here
if(hostMatrix[i * cols + j] != 0){
sum += hostMatrix[i * cols + j];
counter++;
}
}
sum=sum/counter;
sums[i] = sum;
}
System.out.println("sums of the columns ");
for(int i=0;i<rows;i++){
System.out.println(" "+sums[i]);
}
```

Source (Stackoverflow)

Comments