gpt4 book ai didi

arrays - 当输出维度超过输入维度时,Julia `mapslices`

转载 作者:行者123 更新时间:2023-12-02 18:44:49 25 4
gpt4 key购买 nike

我正在尝试将函数 f(x::Array{Float64, 1}) -> Array{Float64, 2} 应用于 m x n 中的每一行> Julia 中的数组(我正在使用 v1.1,如果相关的话)。

现在,我希望我可以简单地应用mapslices,如下所示:

# toy example of f
f = (x -> randn(length(x), length(x)))
A = randn(100, 50)

# intent: apply f to every row in A and collect the result into a 100 x 50 x 50 matrix.
result = mapslices(f, A, dims=2)

不幸的是,mapslices 失败并显示以下消息:

ERROR: DimensionMismatch("tried to assign 2 elements to 1 destinations")

是否有一个mapslices可以模拟这种情况?我知道我可以使用 for 循环来完成此操作,但我希望能更简单。

更新:显然,一种方法是将 A 嵌入到 3-D 数组中:

result = mapslices(f, reshape(A, (size(A)..., 1)), dims=[2, 3])

最佳答案

我只尝试过 Julia v1.6,但我认为你可以用 eachrow (出现在 Julia v1.1 中)非常字面地“将 f 应用到每一行” ):

julia> f(x) = randn(length(x), length(x))
f (generic function with 1 method)

julia> A = rand(3,2)
3×2 Matrix{Float64}:
0.47239 0.179252
0.542389 0.25828
0.0513623 0.630193

julia> f.(eachrow(A))
3-element Vector{Matrix{Float64}}:
[-2.183245554875081 -0.16762649791435957; 0.9124553173227186 0.9148972946316921]
[-0.7322553194397725 -0.5844536492551982; 0.37738478201981623 -0.7056092457600269]
[1.0091890849396576 1.6451194487283958; 0.674221636656597 1.0509408618443663]

关于arrays - 当输出维度超过输入维度时,Julia `mapslices`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67594415/

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