Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply function elementwise in Julia?

Tags:

julia

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

Let's suppose I'd like to plot it and get X and Y. One possible way to do it is following

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

But, it seems like it's also possible to do the same using elementwise operator in Julia?

Unfortunately prefixing the function with the dot .h(X) doesn't work.

like image 434
Alexey Petrushin Avatar asked Apr 01 '16 05:04

Alexey Petrushin


People also ask

How do you use functions in Julia?

Functions in Julia can be combined by composing or piping (chaining) them together. Function composition is when you combine functions together and apply the resulting composition to arguments. You use the function composition operator ( ∘ ) to compose the functions, so (f ∘ g)(args...) is the same as f(g(args...)) .

How do you use vector in Julia?

A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector. vector_name = [value1, value2, value3,..] or vector_name = Vector{Datatype}([value1, value2, value3,..])

How do I return a value to Julia?

'return' keyword in Julia is used to return the last computed value to the caller function. This keyword will cause the enclosing function to exit once the value is returned. return keyword will make the function to exit immediately and the expressions after the return statement will not be executed.


1 Answers

update: f.(x) syntax was merged and avaliable in julia v0.5, see the document or WIP.

@vectorize_1arg in julia's Base can make Arrays acceptable by your functions. Wrap your h with this macro may 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 add new grammars for this problem.

like image 197
张实唯 Avatar answered Oct 21 '22 01:10

张实唯