将函数应用于Julia中的成对的列

时间:2019-05-11 21:25:30

标签: arrays loops functional-programming julia

我有一对尺寸相等的矩阵Ws, Xs和一个函数myFunc(w, x),该函数将两个向量作为输入。我想将此功能应用于成对的列(将其视为zip-插入列)并将该功能映射到它们。

是否有一种非迭代的方式来做到这一点?如果Ws, Xs的每个中只有两列,我可以做

allCols = permutedims(reshape(hcat(Ws, Xs), d, 2), [1, 3, 2])
mapslices(x -> myFunc(x[:, 1], x[:, 2]), allCols, dims=[1, 2])

但是我在移到任意列数时遇到了麻烦。

编辑:使用vcat,正确的尺寸似乎可以解决此问题:

# assume d is column size
wxArray = reshape(vcat(Ws, Xs), 2, d)  # group pairs of columns together
mapslices(x -> myFunc(x[:, 1], x[:, 2]), wxArray, dims=[1,2])

1 个答案:

答案 0 :(得分:2)

您可以像这样使用eachcol函数(我给出了三种方法来展示不同的方法,但是eachcol在所有方法中都是至关重要的):

julia> Ws = rand(2,3)
2×3 Array{Float64,2}:
 0.164036  0.233236  0.937968
 0.724233  0.102248  0.55047

julia> Xs = rand(2,3)
2×3 Array{Float64,2}:
 0.0493071  0.735849  0.643352
 0.909295   0.276808  0.396145

julia> using LinearAlgebra

julia> dot.(eachcol(Ws), eachcol(Xs))
3-element Array{Float64,1}:
 0.6666296397421881
 0.19992972241709792
 0.8215096642236619

julia> dot.(eachcol.((Ws, Xs))...)
3-element Array{Float64,1}:
 0.6666296397421881
 0.19992972241709792
 0.8215096642236619

julia> map(dot, eachcol(Ws), eachcol(Xs))
3-element Array{Float64,1}:
 0.6666296397421881
 0.19992972241709792
 0.8215096642236619

这需要Julia 1.1。

编辑

如果您使用的是Julia 1.0,并且确实想避免迭代而又不介意一些额外的分配(上述解决方案避免了分配),则还可以使用cat函数(比我认为的方法要简单一些) :

julia> Ws = rand(2,3)
2×3 Array{Float64,2}:
 0.975749  0.660932  0.391192
 0.619872  0.278402  0.799096

julia> Xs = rand(2,3)
2×3 Array{Float64,2}:
 0.0326003  0.272455  0.713046
 0.389058   0.886105  0.950822

julia> mapslices(x -> (x[:,1], x[:,2]), cat(Ws, Xs; dims=3), dims=[1,3])[1,:,1]
3-element Array{Tuple{Array{Float64,1},Array{Float64,1}},1}:
 ([0.975749, 0.619872], [0.0326003, 0.389058])
 ([0.660932, 0.278402], [0.272455, 0.886105])
 ([0.391192, 0.799096], [0.713046, 0.950822])

当然,您也可以简单地这样做:

julia> map(i -> (Ws[:,i], Xs[:,i]), axes(Ws, 2))
3-element Array{Tuple{Array{Float64,1},Array{Float64,1}},1}:
 ([0.975749, 0.619872], [0.0326003, 0.389058])
 ([0.660932, 0.278402], [0.272455, 0.886105])
 ([0.391192, 0.799096], [0.713046, 0.950822])

或更喜欢:

julia> (i -> (Ws[:,i], Xs[:,i])).(axes(Ws, 2))
3-element Array{Tuple{Array{Float64,1},Array{Float64,1}},1}:
 ([0.975749, 0.619872], [0.0326003, 0.389058])
 ([0.660932, 0.278402], [0.272455, 0.886105])
 ([0.391192, 0.799096], [0.713046, 0.950822])