coo*_*lsv 5 function apply julia
我在 Julia 中创建了以下函数:
using StatsBase
function samplesmallGram(A::AbstractMatrix)
n=size(A,1)
kpoints=sort(sample((1:n),Int(0.05*n),replace=false))
Lsmall=A[kpoints,kpoints]
return kpoints,Lsmall
end
Run Code Online (Sandbox Code Playgroud)
我想L
通过map()
命令而不是for
循环将此函数应用于我拥有的对称方阵 10 次。我试过
map(samplesmallGram(L), 1:1:10)
Run Code Online (Sandbox Code Playgroud)
但它不起作用...我怎样才能实现这个目标?
通常,map 用于集合的每个元素,就像每个元素的转换过程一样。
https://docs.julialang.org/en/v1/base/collections/index.html#Base.map
julia> map(x -> x * 2, [1, 2, 3])
3-element Array{Int64,1}:
2
4
6
julia> map(+, [1, 2, 3], [10, 20, 30])
3-element Array{Int64,1}:
11
22
33
Run Code Online (Sandbox Code Playgroud)
还要看看减速器的想法。它们是相关的。
您可以将 L 作为全局变量传递,也可以在调用时使用箭头表示法。
output = map(x -> samplesmallGram(L), 1:1:10)
Run Code Online (Sandbox Code Playgroud)
请注意,在本例中 x 不是函数的参数,而是 L 被传递了 10 次。
A = []
function samplesmallGram(index)
global A
n=size(A,1)
kpoints=sort(sample((1:n),Int(0.05*n),replace=false))
Lsmall=A[kpoints,kpoints]
return kpoints,Lsmall
end
output = map(samplesmallGram, 1:1:10)
Run Code Online (Sandbox Code Playgroud)
希望有帮助。
map
假设它的第一个参数从您迭代的集合中获取元素,因此您必须编写:
map(_ -> samplesmallGram(L), 1:1:10)
Run Code Online (Sandbox Code Playgroud)
或者
map(1:1:10) do _
samplesmallGram(L)
end
Run Code Online (Sandbox Code Playgroud)
我表示_
我不打算使用这个论点。
然而,在这种情况下,我通常更喜欢写这样的理解:
[samplesmallGram(L) for _ in 1:1:10]
Run Code Online (Sandbox Code Playgroud)
(作为旁注:1:1:10
您也可以写1:10
)