Calculating mean value in the metal kernel
<p>Anyone knows a proper way to calculate mean value of the buffer with random float numbers in the metal kernel?</p>

<p>Dispatching work on the compute command encoder:</p>

<pre><code>threadsPerGroup = MTLSizeMake(1, 1, inputTexture.arrayLength);
numThreadGroups = MTLSizeMake(1, 1, inputTexture.arrayLength / threadsPerGroup.depth);

[commandEncoder dispatchThreadgroups:numThreadGroups
               threadsPerThreadgroup:threadsPerGroup];
</code></pre>

<p>Kernel code:</p>

<pre><code>kernel void mean(texture2d_array&lt;float, access::read&gt; inTex [[ texture(0) ]],
             device float *means                            [[ buffer(1) ]],
             uint3 id                                       [[ thread_position_in_grid ]]) {

    if (id.x == 0 &amp;&amp; id.y == 0) {
        float mean = 0.0;
        for (uint i = 0; i &lt; inTex.get_width(); ++i) {
            for (uint j = 0; j &lt; inTex.get_height(); ++j) {
                    mean += inTex.read(uint2(i, j), id.z)[0];
            }
        }

        float textureArea = inTex.get_width() * inTex.get_height();
        mean /= textureArea;
        out[id.z] = mean;
    }
}
</code></pre>

<p>The buffer is represented in the texture of texture2d_array type with R32Float pixel format.</p>