How to apply elementwise function in Julia?

There is a function h(x) = ([1, x]' * [2, 3])[1]

Suppose I would like to build it and get X and Y One possible way to do this is:

 X = [1 2 3] Y = [h(xi) for xi in X] 

But it seems you can also do the same with the elementary operator in Julia?

Unfortunately, the function prefix with the dot .h(X) does not work.

+5
source share
1 answer

update : f.(x) syntax has been merged and is available in julia v0.5, see document or WIP .

@ vectorize_1arg in julia Base can make arrays acceptable by your functions. Wrap your h so this macro can solve the problem.

Here is an example from julia document

 julia> square(x) = x^2 square (generic function with 1 method) julia> @vectorize_1arg Number square square (generic function with 4 methods) julia> methods(square) # 4 methods for generic function "square": square{T<:Number}(::AbstractArray{T<:Number,1}) at operators.jl:380 square{T<:Number}(::AbstractArray{T<:Number,2}) at operators.jl:381 square{T<:Number}(::AbstractArray{T<:Number,N}) at operators.jl:383 square(x) at none:1 julia> square([1 2 4; 5 6 7]) 2x3 Array{Int64,2}: 1 4 16 25 36 49 

If you are looking for a more โ€œelegantโ€ method, here is a discussion about adding new grammars for this problem.

+11
source

Source: https://habr.com/ru/post/1246203/


All Articles