Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map function with arguments in Julia

I created the following function in 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

I want to apply this function 10 times to a square symmetric matrix L I have, through the map() command, instead of a for loop. I tried

map(samplesmallGram(L), 1:1:10)

but it doesn't work... How can I achieve this?

like image 454
coolsv Avatar asked Mar 03 '23 16:03

coolsv


2 Answers

Typically map is used on each element of a collection, like a conversion process for each element.

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

Also look at the idea of reducers. They are related.

You can either pass in L as a global, or use the arrow notation when making the call.

Arrow Notation

output = map(x -> samplesmallGram(L), 1:1:10)

Note that x is not the argument to the function in this case, instead L is passed in 10 times.

Global

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)

Hope that helps.

like image 198
phyatt Avatar answered Mar 06 '23 04:03

phyatt


map assumes that its first argument takes elements from the collection you iterate over, so you have to write:

map(_ -> samplesmallGram(L), 1:1:10)

or

map(1:1:10) do _
    samplesmallGram(L)
end

By _ I indicate that I do not intend to use this argument.

However, in such cases I typically prefer to write a comprehension like this:

[samplesmallGram(L) for _ in 1:1:10]

(as a side note: instead of 1:1:10 you can also write 1:10)

like image 43
Bogumił Kamiński Avatar answered Mar 06 '23 04:03

Bogumił Kamiński