說我有以下功能
function foo(p :: Int, x :: Real)
return p*x
end
我想為以下陣列呼叫它:
P = [1, 2, 3]
X = [5.0, 6.0, 7.0, 8.0]
如果我想呼叫foo并將值存盤在單個大小的陣列中,(length(P), length(X))我可以雙回圈X并P作為:
R = zeros(length(P), length(X))
for i in 1:length(P), j in 1:length(X)
R[i, j] = foo(P[i], X[j])
end
但是,是否有另一種方法可以在明確避免雙回圈的同時做到這一點?也許像什么?
R = foo.(collect(zip(P, X)))
當然,上述foo方法無法處理::Tuple{Int64, Float64},但我暫時還沒有找到一種方法來廣播不同大小的陣列。任何提示將不勝感激,謝謝!
uj5u.com熱心網友回復:
如果你想使用廣播,你可以這樣做:
julia> foo.(P, permutedims(X))
3×4 Matrix{Float64}:
5.0 6.0 7.0 8.0
10.0 12.0 14.0 16.0
15.0 18.0 21.0 24.0
要么
julia> foo.(P, reshape(X, 1, :))
3×4 Matrix{Float64}:
5.0 6.0 7.0 8.0
10.0 12.0 14.0 16.0
15.0 18.0 21.0 24.0
要么
julia> (((x, y),) -> foo(x, y)).(Iterators.product(P, X))
3×4 Matrix{Float64}:
5.0 6.0 7.0 8.0
10.0 12.0 14.0 16.0
15.0 18.0 21.0 24.0
要么
julia> Base.splat(foo).(Iterators.product(P, X))
3×4 Matrix{Float64}:
5.0 6.0 7.0 8.0
10.0 12.0 14.0 16.0
15.0 18.0 21.0 24.0
請注意,伴隨 ( ') 通常在這里不起作用,因為它是遞回的:
julia> x = ["a", "b"]
2-element Vector{String}:
"a"
"b"
julia> permutedims(x)
1×2 Matrix{String}:
"a" "b"
julia> x'
1×2 adjoint(::Vector{String}) with eltype Union{}:
Error showing value of type LinearAlgebra.Adjoint{Union{}, Vector{String}}:
ERROR: MethodError: no method matching adjoint(::String)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/447774.html
上一篇:如何參考字典來填充字串中的變數?
下一篇:從資料框中的字典中提取資訊
