Function vectorization by a specific argument

Suppose I have a function

myfunc(a, x::Int64) = a * x 

I only want to vectorize the second argument, so I have something like

 myfunc{N}(a, x::Array{Int64, N}) = map(x -> myfunc(a, x), x) 

I know there is a macro @ vectorize_1arg or @ vectorize_2arg. However, these macros will vectorize all arguments.

Question: How is it convenient to vectorize a function by a specific argument? Should I have hard code like in the above example?

+6
source share
1 answer

If you want to extend functions that only require the vectors of the arg vector, this should do this:

 macro vectorize_on_2nd(S, f) S = esc(S); f = esc(f); N = esc(:N) quote ($f){$N}(a, x::AbstractArray{$S, $N}) = reshape([($f)(a, x[i]) for i in eachindex(x)], size(x)) end end 

Used as follows:

 @vectorize_on_2nd Int64 myfunc 

This should give you the myfunc{N}(::Any, ::AbstractArray{Int64,N}) method myfunc{N}(::Any, ::AbstractArray{Int64,N}) .

+4
source

All Articles