Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 816
Suvar Avatar asked Aug 07 '26 06:08

Suvar


2 Answers

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
like image 153
Bogumił Kamiński Avatar answered Aug 08 '26 21:08

Bogumił Kamiński


One possible solution is to create an anonymous function inside map as follows -->

x = [1, 2, 3, 4, 5]
b = 3

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

map(x -> f(x, b), x)

which produces below output-->

5-element Vector{Int64}:
  3
  6
  9
 12
 15

Explanation :- Anonymous function is taking values from vector as its first argument and 2nd argument is fixed with b = 3.

like image 32
KARTHIK D K Avatar answered Aug 08 '26 22:08

KARTHIK D K