Search code examples
vectorjuliaapplysapply

Apply function with multiple arguments to a vector in Julia


I would like to apply function with multiple arguments to a vector. It seems that both map() and map!() can be helpful.

It works perfect if function has one argument:

f = function(a)
    a+a
end
x=[1,2,3,4,5]
map(f, x)

output: [2, 4, 6, 8, 10]

However, it is not clear how to pass arguments to the function, if possible, and the vector to broadcast, if the function has multiple arguments.

f = function(a,b)
    a*b
end

However, non of the following working:

b=3

map(f(a,b), x, 3)
map(f, x, 3)
map(f, a=x, b=3)
map(f(a,b), x, 3)
map(f(a,b), a=x,b=3)

Expected output: [3,6,9,12,15]


Solution

  • Use broadcast - just as you suggested in the question:

    julia> f = function(a,b)
               a*b
           end
    #1 (generic function with 1 method)
    
    julia> x=[1,2,3,4,5]
    5-element Vector{Int64}:
     1
     2
     3
     4
     5
    
    julia> b=3
    3
    
    julia> f.(x, b)
    5-element Vector{Int64}:
      3
      6
      9
     12
     15
    

    map does not broadcast, so if b is a scalar you would manually need to write:

    julia> map(f, x, Iterators.repeated(b, length(x)))
    5-element Vector{Int64}:
      3
      6
      9
     12
     15
    

    You can, however, pass two iterables to map without a problem:

    julia> map(f, x, x)
    5-element Vector{Int64}:
      1
      4
      9
     16
     25