Reputation: 27
I am working just recently in Java. And I am still struggling a little bit with Java. The task is to sum the columns and the rows respectively the example looks like that. I managed to get the sum of the columns, but I always end up having the first row repeated in my desired output, how can I delete that error. And just have the desired column sums.
How does it work for sum of rows respectively?
Thank you very much for your help in advance
The code looks like that:
public class MatrixColumnSums {
public static void main(String[] args) {
// TODO Auto-generated method stub
double [][] a = new double [2][3];
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 5;
a[1][2] = 6;
System.out.println( "A");
for (int i = 0; i < a.length; i++) {
String str = "";
for (int j = 0; j < a[i].length; j++) {
str += a[i][j] + "\t";
}
System.out.println(str);
}
// column sums
// creating another matrix to store the sum of columns matrices
double c[] = new double [a[0].length];
// Adding and printing addition of 2 matrices
System.out.println("C");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++)
{
c[j] += a[i][j];
System.out.print(c[j] + "\t");
}
System.out.println();
}
}
}
The output looks like the following:
A
1.0 2.0 3.0
4.0 5.0 6.0
C
1.0 2.0 3.0 ( <= I want to get this row deleted)
5.0 7.0 9.0 ( I just want to have this as my output)
Upvotes: 0
Views: 2797
Reputation: 151
**Matrix column sum **
doOneColumnSum method sum one column.
private static double doOneColumnSum(double[][] arr, int col){
double total = 0;
for (int row = 0; row < arr.length; row += 1){
total += arr[row][col];
}
return total;
}
doColumnSums method sum all column using doOneColumnSum method
public static double[] doColumnSums(double[][] arr)
{
int numColumns = arr[0].length;
double[] result = new double[numColumns];
for (int col = 0; col < numColumns; col += 1)
{
result[col] = findOneColumnSum(arr, col);
}
return result;
}
Upvotes: 1
Reputation: 521289
Don't print when summing the c
matrix, just print once at the end:
// sum the columns first
for (int i=0; i < a.length; i++) {
for (int j=0; j < a[0].length; j++) {
c[j] += a[i][j];
}
}
// then iterate c[] once at the end and print it
for (int j=0; j < a[0].length; j++) {
System.out.print(c[j] + "\t");
}
Note that we could have added if
logic to your original nested loop to only print c
after the summation is complete, but what I wrote above seems more appealing from a separation of concerns point of view.
Upvotes: 0