java - 在java中求矩阵的平均值

标签 java arrays

如何找到 2D 矩阵(5×5)中每 8 个元素的平均值并将其替换为元素号(9)?

Java 编程(OOP)

第一个代码应该像 this 例如:

img
(来源:0zz0.com)

最佳答案

所以我这样做只是为了好玩,这是我的代码。它适用于任何大小的矩阵。

public class Matrixer
{

    final double[][] matrix, computedMatrix;
    final int rows, cols;

    public Matrixer(int N, int M, final double[][] imatrix)
    {
        rows = N;
        cols = M;
        matrix = imatrix;
        computedMatrix = new double[N][M];
    }

    public void computeAverages()
    {
        for (int i = 1; i < rows - 1; i++)
        {
            for (int j = 1; j < cols - 1; j++)
            {
                computedMatrix[i][j] = cellNeighborsAverage(i, j);
            }
        }
    }

    private double cellNeighborsAverage(int row, int col)
    {
        // Ignore center cell
        double sum = matrix[row - 1][col - 1] + matrix[row - 1][col]
                + matrix[row - 1][col + 1] + matrix[row][col - 1]
                + matrix[row][col + 1] + matrix[row + 1][col - 1]
                + matrix[row + 1][col] + matrix[row + 1][col + 1];
        return sum / 8;
    }

    public void printComputedMatrix()
    {
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                System.out.printf("%.2f", computedMatrix[i][j]);
                System.out.print(", ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args)
    {
        final double[][] matrix =
        {
            {1, 2, 3, 4, 5},
            {5, 4, 3, 5, 1},
            {3, 2, 2, 3, 4},
            {2, 3, 4, 5, 3},
            {3, 2, 4, 5, 6},
        };

        Matrixer mx = new Matrixer(5, 5, matrix);
        mx.computeAverages();
        mx.printComputedMatrix();
    }
}

测试输出:

0.00, 0.00, 0.00, 0.00, 0.00, 
0.00, 2.63, 3.13, 3.13, 0.00, 
0.00, 3.25, 3.63, 3.38, 0.00, 
0.00, 2.75, 3.25, 3.88, 0.00, 
0.00, 0.00, 0.00, 0.00, 0.00

关于java - 在java中求矩阵的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23184503/

相关文章:

java - Cordova 3.5 android 文件插件中的 NullPointer 异常

Java setPressedIcon 不工作

javascript - Javascript 中的最大数组大小

php - 带查询的日期数组

php - 按输入数组的顺序从 elasticsearch 中检索信息

java - 构造函数 PrintWriter(BufferedWriter) 未定义

java - 如何在素数范围程序的输出中打印行号?

java 将 LinkedHashMap 转换为扩展 LinkedHashMap 的类

html - ruby 解析问题

c - 在结构函数中分配动态数组