gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:04:21 26 4
gpt4 key购买 nike

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

我卡在按元素对所有矩阵数组求和的部分。

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

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

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

最佳答案

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

julia> x = rand(2,2,1000);

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

sum(A::AbstractArray; dims)

Sum elements of an array over the given dimensions.

在你的情况下,

julia> result = sum(x, dims=3);

但是请注意,结果仍将具有 3 个维度,这可以通过 ndims 或通过使用 typeof 检查类型来检查:

julia> ndims(result)
3

julia> typeof(result)
Array{Float64,3}

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

julia> size(result)
(2, 2, 1)

可以删除它以提供所需的 2x2 矩阵结果

julia> dropdims(result, dims=3)
2×2 Array{Float64,2}:
510.444 503.893
489.592 480.065

总的来说,dropdims(sum(x, dims=3), dims=3)

备注(更新)

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

julia> function f(x::AbstractArray{<:Number, 3})
nrows, ncols, n = size(x)
result = zeros(eltype(x), nrows, ncols)
for k in 1:n
for j in 1:ncols
for i in 1:nrows
result[i,j] += x[i,j,k]
end
end
end
result
end
f (generic function with 1 method)

julia> @btime dropdims(sum($x, dims=3), dims=3);
7.034 μs (19 allocations: 592 bytes)

julia> @btime f($x);
5.205 μs (1 allocation: 112 bytes)

关于julia - 对给定维度的数组元素求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53076017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com