如何实现特定一维数组的列均值计算算法?
一维数组列均值计算算法实现(C#)
问题说明
输入的一维数组是10行×1024列的矩阵按行拼接而来(先存第1行的1024个元素,再存第2行,以此类推),需要计算每一列的平均值,最终得到长度为1024的结果数组,每个元素对应原矩阵对应列的均值。
核心思路
- 固定矩阵维度:列数(宽度)1024,行数(高度)10
- 遍历每一列,累加该列所有行的元素值
- 将累加和除以行数,得到该列的均值,存入结果数组
C# 实现代码
处理浮点型数组
public static double[] CalculateColumnAverages(double[] flattenedMatrix) { const int ColumnCount = 1024; const int RowCount = 10; double[] columnAverages = new double[ColumnCount]; // 遍历每一列 for (int col = 0; col < ColumnCount; col++) { double columnSum = 0; // 累加当前列的所有行元素 for (int row = 0; row < RowCount; row++) { // 一维数组索引计算:行号×列数 + 列号 int arrayIndex = row * ColumnCount + col; columnSum += flattenedMatrix[arrayIndex]; } // 计算均值 columnAverages[col] = columnSum / RowCount; } return columnAverages; }
处理整数型数组(避免溢出与除法误差)
如果输入是整数数组,建议用long存储累加和避免溢出,同时转换为浮点型计算均值:
public static double[] CalculateColumnAverages(int[] flattenedMatrix) { const int ColumnCount = 1024; const int RowCount = 10; double[] columnAverages = new double[ColumnCount]; for (int col = 0; col < ColumnCount; col++) { long columnSum = 0; for (int row = 0; row < RowCount; row++) { int arrayIndex = row * ColumnCount + col; columnSum += flattenedMatrix[arrayIndex]; } // 转为double计算均值,避免整数除法截断 columnAverages[col] = (double)columnSum / RowCount; } return columnAverages; }
其他语言参考(Python)
def calculate_column_averages(flattened_matrix): column_count = 1024 row_count = 10 averages = [] for col in range(column_count): # 累加当前列的所有元素 total = sum(flattened_matrix[row * column_count + col] for row in range(row_count)) averages.append(total / row_count) return averages
内容的提问来源于stack exchange,提问作者GNZ
相关产品推荐
相关产品推荐

