# 在java中查找矩阵的平均值find average of a matrix in java [closed]

（来源： 0zz0.com

## 2 个回复2

### ===============>>#1 票数：1 已采纳

``````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
``````

### ===============>>#2 票数：0

``````var myMatrix = [
[ x, x, x, x, x],
[ x, x, x, x, x],
[ x, x, x, x, x],
[ x, x, x, x, x],
[ x, x, x, x, x] ];

function neighborAverage(row, col) {
return (( myMatrix[row-1][col-1] +
myMatrix[row-1][col] +
myMatrix[row-1][col+1] +
myMatrix[row][col-1] +
// skip the center element
myMatrix[row][col+1] +
myMatrix[row+1][col-1] +
myMatrix[row+1][col] +
myMatrix[row+1][col+1]) / 8));
}

function matrixAverage() {
return ([
[ neighborAverage(1, 1), neighborAverage(1, 2), neighborAverage(1, 3) ],
[ neighborAverage(2, 1), neighborAverage(2, 2), neighborAverage(2, 3) ],
[ neighborAverage(3, 1), neighborAverage(3, 2), neighborAverage(3, 3) ] ]);
}
``````

• `matrixAverage()`硬编码索引表示此伪代码仅适用于大小为5x5的矩阵。 但是，泛化该函数以使用任何大小的矩阵都应该很容易。

• 该伪代码计算所有平均值，但不会覆盖原始矩阵中的任何值。 那可能是您想要的，也可能不是您想要的，因为您没有指定是否应使用每个新值来计算后续值（如果这样，则应以什么顺序计算值）。

2回复

1回复

1回复

6回复

1回复

4回复

1回复

8回复

4回复

3回复