对给定维度上的数组元素求和

big*_*123 5 julia

我对 Julia 很陌生,通过做一些项目来学习这些东西。

我陷入了按元素对所有矩阵数组求和的部分。

我有 2 * 2 * 1000 3 维数组。基本上,它是关于找到 1000 个样本的平均方差-协方差矩阵。它迭代 1 到 1000。

我尝试使用 Sum 命令,但它给了我标量。我需要 [2,2,1] + [2,2,2] + [2,2,3] + ... [2,2,100] = (2 x 2 矩阵)

有没有不使用循环的简单方法?

crs*_*nbr 7

正如评论中已经指出的,如果你有一个 3 维数组,

\n\n
julia> x = rand(2,2,1000);\n
Run Code Online (Sandbox Code Playgroud)\n\n

您可以使用(取自?sum)对任何维度求和

\n\n
\n

sum(A::AbstractArray; dims)

\n\n

对给定维度上的数组元素求和。

\n
\n\n

就你而言,

\n\n
julia> result = sum(x, dims=3);\n
Run Code Online (Sandbox Code Playgroud)\n\n

但请注意,结果仍然具有 3 个维度,可以通过ndims或 通过检查类型来检查typeof

\n\n
julia> ndims(result)\n3\n\njulia> typeof(result)\nArray{Float64,3}\n
Run Code Online (Sandbox Code Playgroud)\n\n

出现这种行为的原因是类型稳定性。我们总结的第三个维度将是一个单一维度,

\n\n
julia> size(result)\n(2, 2, 1)\n
Run Code Online (Sandbox Code Playgroud)\n\n

可以删除它以给出所需的 2x2 矩阵结果

\n\n
julia> dropdims(result, dims=3)\n2\xc3\x972 Array{Float64,2}:\n 510.444  503.893\n 489.592  480.065\n
Run Code Online (Sandbox Code Playgroud)\n\n

总共,dropdims(sum(x, dims=3), dims=3)

\n\n

备注(更新)

\n\n

Julia 中的循环速度很快。因此,如果不仅仅是为了方便,您可以通过使用循环实现更快地获得结果,例如

\n\n
julia> function f(x::AbstractArray{<:Number, 3})\n           nrows, ncols, n = size(x)\n           result = zeros(eltype(x), nrows, ncols)\n           for k in 1:n\n               for j in 1:ncols\n                   for i in 1:nrows\n                       result[i,j] += x[i,j,k]\n                   end\n               end\n           end\n           result\n       end\nf (generic function with 1 method)\n\njulia> @btime dropdims(sum($x, dims=3), dims=3);\n  7.034 \xce\xbcs (19 allocations: 592 bytes)\n\njulia> @btime f($x);\n  5.205 \xce\xbcs (1 allocation: 112 bytes)\n
Run Code Online (Sandbox Code Playgroud)\n