Julia's equivalent to Fortran elemental functions

Fortran has elemental functions.

This means that you can define a function for primitive types (int, double…) and they will automatically work for vectors and matrices that contain these primitive types.

Consider the elemental function pos(x::Number) = x < 0 ? zero(x) : x

This is the closest I get using Julia:

pos(x) = reshape([pos(x[i]) for i = 1:length(x)],size(x))

Now pos works for scalars of type Number, vectors, matrices, ranges…

Are there alternatives?

You can vectorize any function by adding a dot:

pos.(my_array)
1 Like

In 0.5 and later, this is exactly what . broadcasting is for:

julia> pos(x::Number) = x < 0 ? zero(x) : x
pos (generic function with 1 method)

julia> pos.(randn(10))
10-element Array{Float64,1}:
 0.0     
 0.0     
 0.0     
 0.0     
 0.0     
 0.455044
 0.0     
 0.639169
 0.636522
 1.07678 

See Steven G. Johnson’s excellent blog post for more details.

4 Likes

Simply amazing.

Thanks!

2 Likes