我需要以尺寸方式计算数组的平均值

I need to calculate the mean value of an array in a dimension-wise fashion

本文关键字:计算 数组 平均值 方式      更新时间:2023-10-16

我开始学习C ,并在Python中有更多的经验。

我有以下用Python编写的代码,该代码从3D数组返回Z-Dimension

中平均值的2D数组
import numpy as np
def mean_py_st_ov(array):
    x = array.shape[1]
    y = array.shape[2]
    values = np.empty((x,y), type(array[0][0][0]))
    for i in range(x):
        for j in range(y):       
            values[i][j] = ((np.mean(array[:, i, j])))
    return values

我正在研究以下代码,以返回3D数组的ndimension中的平均值,但是到现在为止。我正在努力一次尝试在每个维度中获取I-J元素。

// C++ program to print elements of Three-Dimensional 
// Array 
#include<iostream> 
using namespace std; 
int main() 
{ 
    // initializing the 3-dimensional array 
    int x[3][2][2] = 
    { 
        { {0,1}, {2,3} },
         {{4,5}, {6,7}}, 
         {{8,9}, {10,11} } 
    }; 
    // output each element's value 
    for (int k = 0; k < 3; ++k) 
    { 
        for (int i = 0; i < 2; ++i) 
        { 
            for (int j = 0; j < 2; ++j) 
            { 
                cout << "Element at x[" << k << "][" << i 
                    << "][" << j << "] = " << x[k][i][j] 
                    << endl; 
            } 
        } 
    } 
    return 0; 
} 

我收到以下输出

Element at x[0][0][0] = 0
Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
Element at x[0][1][1] = 3
Element at x[1][0][0] = 4
Element at x[1][0][1] = 5
Element at x[1][1][0] = 6
Element at x[1][1][1] = 7
Element at x[2][0][0] = 8
Element at x[2][0][1] = 9
Element at x[2][1][0] = 10
Element at x[2][1][1] = 11

我想要的是说... 1 array的第一个元素,其中第二个数组的第一个元素,然后是1 array中的第二个元素,带有2 array的第二个元素。我只以这种方式迭代了所有示例i,j,k,它按照我想要的不是我想要的所有元素打印所有元素,因为我需要在3D数组中的z轴上获得均值。<<<<<<<<<<<<<<<<

我需要以下输出:

    Element at x[0][0][0] = 0
    Element at x[1][0][0] = 4
    Element at x[2][0][0] = 8
    Element at x[0][0][1] = 1
    Element at x[1][0][1] = 5
    Element at x[2][0][1] = 9
    Element at x[0][1][0] = 2
    Element at x[1][1][0] = 6
    Element at x[2][1][0] = 10
    Element at x[0][1][1] = 3
    Element at x[1][1][1] = 7
    Element at x[2][1][1] = 11

你能帮我!

非常感谢

pd:作为附加奖励点:我想获得z轴中每个元素的平均值,并能够产生以下2D数组作为输出。 int x [2] [2] = {{4,5} {6,7}}}

您需要更改前面的前面:

 for (int i = 0; i < 2; ++i)
{
    for (int j = 0; j < 2; ++j)
    {
        for (int k = 0; k < 3; ++k)
        {
            cout << "Element at x[" << k << "][" << i
                 << "][" << j << "] = " << x[k][i][j]
                 << endl;
        }
    }
}

更快更改的索引应该是最重要的,而变化的索引比其他索引要比其他索引少。