L. Klum
L. Klum

Reputation: 39

Convert array to a list-Julia

I am wanting to use the dbeta function in the Rmath package of Julia with the following call:

dbeta(x, 1, 25)

x is a 100 X 1 array, and when I try to use x with the dbeta function I get the following error:

ERROR: MethodError: no method matching dbeta(::Array{Float64,2}, ::Int64, ::Int64)

Is there a way to convert an array of numbers to a list of numbers in Julia? I am basically trying to work around the fact that x is an array. Thank you!

Upvotes: 1

Views: 1850

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69829

Rmath version 0.4.0 has the following methods for dbeta:

julia> methods(dbeta)
# 2 methods for generic function "dbeta":
dbeta(x::Number, p1::Number, p2::Number) in Rmath at Rmath\src\Rmath.jl:192
dbeta(x::Number, p1::Number, p2::Number, give_log::Bool) in Rmath at Rmath\src\Rmath.jl:209

Which shows you that dbeta expects a scalar as its firs argument. Actually you get this hint when you run dbeta(x, 1, 25):

julia> dbeta(x, 1, 25)
ERROR: MethodError: no method matching dbeta(::Array{Float64,2}, ::Int64, ::Int64)
Closest candidates are:
  dbeta(::Number, ::Number, ::Number) at \Rmath\src\Rmath.jl:192
  dbeta(::Number, ::Number, ::Number, ::Bool) at v0.6\Rmath\src\Rmath.jl:209

which guides you at the proper method signatures.

So how to solve your problem - this is pretty simple. Use broadcasting with . like this:

dbeta.(x, 1, 25)

and all works as expected. In general you can expect that this pattern should be used in almost all functions in Julia, like sin or cos in base, i.e. by default they accept scalars and you should use broadcasting with . to apply them to a vector. This is explained here https://docs.julialang.org/en/latest/manual/functions/#man-vectorized-1 in the Julia manual.

Upvotes: 3

Related Questions