如何计算2d数组中每列的平均值?

ttisahbt  于 2021-07-03  发布在  Java
关注(0)|答案(4)|浏览(475)

我试图计算2d数组中列的平均值,但我无法理解代码。函数应该返回每列的平均值。我无法在函数中打印结果。打印应该是主要功能。

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;
}
o7jaxewo

o7jaxewo1#

如果你假设 NxN 矩阵,可以用流求解:

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());

或更具可读性:

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());

对矩阵进行转置,然后使用 Arrays.stream(...).average().getAsDouble() 计算数组的平均值。

owfi6suc

owfi6suc2#

你可以用 Stream.reduce 方法汇总列中的元素,然后将每个总和除以列数:

double[][] matrix = {
        {1.11, 2.22, 3.33, 4.45, 5.56},
        {6.61, 7.76, 8.88, 9.9, 10.11},
        {11.1, 12.2, 13.3, 14.4, 15.5},
        {16.6, 17.7, 18.8, 19.9, 20.0},
        {21.1, 22.2, 23.3, 24.4, 25.5}};

double[] average = Arrays.stream(matrix)
        // summarize in pairs
        // the rows of the matrix
        .reduce((row1, row2) ->
                // iterate over the indices
                // from 0 to row length
                IntStream.range(0, row1.length)
                        // summarize in pairs the
                        // elements of two rows
                        .mapToDouble(i -> row1[i] + row2[i])
                        // an array of sums
                        .toArray())
        // stream containing
        // the resulting array
        // Stream<double[]>
        .stream()
        // iterate over the array of sums
        // Stream<double[]> to DoubleStream
        .flatMapToDouble(Arrays::stream)
        // divide each element by
        // the number of columns
        .map(i -> i / matrix.length)
        .toArray();

System.out.println(Arrays.toString(average));
// [11.304, 12.416, 13.522, 14.61, 15.334]

另请参见:将二维数组中每列的所有元素相加

ncecgwcz

ncecgwcz3#

你需要退票 double[] 而不是 double 从函数中。
因为数字是一种类型, double ,类型 sum 应该是 double .
如果所有行长度相等:
因为要添加每列的值,所以应该添加 matrix[j][i] (代替 matrix[i][j] )至 sum 因此 average[i]sum / matrix.length .
演示:

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;
    }
}

输出:

[5.333333333333333, 9.0, 12.666666666666666]

如果行的长度不同:
您应该首先找到行的最大长度,它将成为 double[] average .
最后,使用两级嵌套循环来计算 average[] . 外环将到达 average.length 内部循环将达到行数。在处理每一列时,使用计数器(例如。 int count )跟踪添加到的值的数量 sum . 在内环的末端, average[i] = sum / count .
演示:

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;
    }
}

输出:

[5.333333333333333, 9.0, 17.5, 25.0]
zaqlnxep

zaqlnxep4#

这就是如何计算每行和每列的总和和平均值:下面的示例代码将以相同的方法打印总和和平均值,并且不会返回任何值。如果您需要返回实际的总和和平均值,那么您需要返回double[],它将包含所有总和或平均值,而不是double。
代码

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; 
        } 
    } 

}

输出

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

相关问题