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.
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...)) .
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,..])
'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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With