¿Cómo calcular el valor promedio de cada columna en una matriz 2D?

Nov 30 2020

Estoy tratando de calcular el valor promedio de las columnas en una matriz 2D, pero no puedo descifrar el código. La función debe devolver el valor promedio de cada columna. Y no puedo imprimir el resultado en la función. La impresión debe estar en función principal.

static double average_columns(double matrix[][]) {
    int i, j, sum = 0, average=0;
    for (i = 0; i < matrix.length; i++) {
        for (j = 0; j < matrix[i].length; j++) {
            sum=(int) (sum+matrix[i][j]);
        }
        average=sum/matrix[i].length;
        sum=0;
    }
    return average;
}

Respuestas

1 Som Nov 30 2020 at 12:34

Así es como puede calcular la suma y los promedios de cada fila y columna: El siguiente código de ejemplo imprimirá la suma y los promedios en el mismo método y no devolverá ningún valor. Si necesita devolver la suma real y el promedio, deberá devolver el doble [], que contendrá todas las sumas o promedios en lugar de un doble.

CÓDIGO

public class Test {
    
    static int m = 3; 
    static int n = 3; 

    public static void main(String[] args) {
        
        int i,j;
        int [][]matrix = new int[m][n]; 
      
        int x = 1; // x fills up the value of the matrix
        for (i = 0; i < m; i++) 
            for (j = 0; j < n; j++) 
                matrix[i][j] = x++; 
      
        
        System.out.println("The matrix is : \n");
        for (i = 0; i < m; i++) {
            for (j = 0; j < n; j++) {
                System.out.print(matrix[i][j] + "    ");
            }
            System.out.println();
        }
        
        System.out.println("\nPrinting the avg of each col ::");
        average_columns(matrix);
        
        System.out.println("\nPrinting the avg of each row ::");
        average_rows(matrix);
        
        System.out.println("\nPrinting the sum of each col ::");
        sum_columns(matrix);
        
        System.out.println("\nPrinting the sum of each row ::");
        sum_rows(matrix);

    }
    
    public static void average_rows(int matrix[][]) {
        int i, j;
        double sum = 0, average = 0;
        for (i = 0; i < matrix.length; i++) {
            for (j = 0; j < matrix[i].length; j++) {
                sum=sum+matrix[i][j];
            }
            average=sum/matrix[i].length;
            System.out.println("Average of row " + (i+1) + " = " + average); 
            sum=0;
        }
    }
    
    public static void average_columns(int matrix[][]) {
        int i, j;
        double sum = 0, average = 0;
        for (i = 0; i < matrix.length; i++) {
            for (j = 0; j < matrix[i].length; j++) {
                sum=sum+matrix[j][i];
            }
            average=sum/matrix[i].length;
            System.out.println("Average of column " + (i+1) + " = " + average);
            sum=0;
        }
    }
    
    public static void sum_columns(int matrix[][]) { 
          
        int i,j;
        double sum = 0;       
        for (i = 0; i < matrix.length; ++i) { 
            for (j = 0; j < matrix.length; ++j) { 
                sum = sum + matrix[j][i]; 
            } 
            System.out.println("Sum of column " + (i+1) + " = " + sum); 
            sum = 0; 
        } 
    } 
    
    public static void sum_rows(int matrix[][]) { 
          
        int i,j;
        double sum = 0;   
        for (i = 0; i < matrix.length; ++i) { 
            for (j = 0; j < matrix.length; ++j) { 
                sum = sum + matrix[i][j]; 
            } 
            System.out.println( "Sum of row " + (i+1) + " = " + sum); 
            sum = 0; 
        } 
    } 


}

SALIDA

The matrix is : 

1    2    3    
4    5    6    
7    8    9    

Printing the avg of each col ::
Average of column 1 = 4.0
Average of column 2 = 5.0
Average of column 3 = 6.0

Printing the avg of each row ::
Average of row 1 = 2.0
Average of row 2 = 5.0
Average of row 3 = 8.0

Printing the sum of each col ::
Sum of column 1 = 12.0
Sum of column 2 = 15.0
Sum of column 3 = 18.0

Printing the sum of each row ::
Sum of row 1 = 6.0
Sum of row 2 = 15.0
Sum of row 3 = 24.0
dreamcrash Nov 30 2020 at 15:41

Si asume una NxNmatriz, puede resolverlo con flujos:

double[][] matrix = { { 1, 5, 15}, { 1, 2, 2}, { 25, 109, 150} };

List<Double> column_average = Arrays.stream(IntStream.range(0, matrix[0].length)
            .mapToObj(c1 -> Arrays.stream(matrix).mapToDouble(doubles -> doubles[c1]).toArray())
            .toArray(double[][]::new))
            .map(i -> Arrays.stream(i).average().getAsDouble())
            .collect(Collectors.toList());

o más legible

 double[][] matrix_transpose = IntStream.range(0, matrix[0].length)
            .mapToObj(c -> Arrays.stream(matrix).mapToDouble(doubles -> doubles[c]).toArray())
            .toArray(double[][]::new);

    List<Double> column_average = Arrays.stream(matrix_transpose)
            .map(col -> Arrays.stream(col).average().getAsDouble())
            .collect(Collectors.toList());

Haces la transposición de la matriz y luego la usas Arrays.stream(...).average().getAsDouble()para calcular los promedios de las matrices.

ArvindKumarAvinash Nov 30 2020 at 12:13
  1. Debe devolver un en double[]lugar de a doublede la función.
  2. Dado que los números son de tipo double, el tipo de sumdebería ser double.

Si todas las filas tienen la misma longitud:

  1. Dado que desea agregar los valores de cada columna, debe agregar matrix[j][i](en lugar de matrix[i][j]) a sumy, en consecuencia, lo average[i]hará sum / matrix.length.

Manifestación:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // Test
        double[][] nums = { { 10, 15, 20 }, { 1, 2, 3 }, { 5, 10, 15 } };
        System.out.println(Arrays.toString(averageColumns(nums)));
    }

    static double[] averageColumns(double matrix[][]) {
        int i, j;
        double[] average = new double[matrix.length];
        for (i = 0; i < matrix.length; i++) {
            double sum = 0;
            for (j = 0; j < matrix[i].length; j++) {
                sum += matrix[j][i];
            }
            average[i] = sum / matrix.length;
        }
        return average;
    }
}

Salida:

[5.333333333333333, 9.0, 12.666666666666666]

Si las filas son de diferente longitud:

  1. Primero debe encontrar el máximo de la longitud de las filas que se convertirá en el tamaño del double[] average.
  2. Finalmente, use un bucle anidado de 2 niveles para calcular los valores de average[]. El bucle exterior se ejecutará hasta average.lengthy el bucle interior se ejecutará hasta el número de filas. Mientras procesa cada columna, use un contador (por ejemplo int count) para realizar un seguimiento del número de valores a los que se agregan sum. Al final del bucle interior, average[i] = sum / count.

Manifestación:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // Test
        double[][] nums = { { 10, 15, 20 }, { 1, 2 }, { 5, 10, 15, 25 } };
        System.out.println(Arrays.toString(averageColumns(nums)));
    }

    static double[] averageColumns(double matrix[][]) {
        // Find the maximum of the length of rows
        int max = matrix[0].length;
        for (int i = 0; i < matrix.length; i++) {
            if (matrix[i].length > max) {
                max = matrix[i].length;
            }
        }

        int i, j;
        double[] average = new double[max];
        for (i = 0; i < average.length; i++) {
            double sum = 0;
            int count = 0;
            for (j = 0; j < matrix.length; j++) {
                if (matrix[j].length - 1 >= i) {
                    sum += matrix[j][i];
                    count++;
                }
            }
            average[i] = sum / count;
        }
        return average;
    }
}

Salida:

[5.333333333333333, 9.0, 17.5, 25.0]