How to correctly put array as an argument in Julia?

Viewed 69

I have a Fortran function like below,

subroutine f(i,weight)
integer(kind=i8) :: i
real(kind=r8) :: weight(i,i)
return 
end

The matrix weight is a i by i matrix, and i is also an argument.

I want the same thing in Julia, I did below

function f(i::Int64, weight::Array{Float64,2}(undef,i,i))
return nothing
end

However it just give me an error,

UndefVarError: i not defined

But if I just do below without the weight matrix as an argument, it does not give error,

function f(i::Int64)
return nothing
end

But obviously this is not what I want.

Or, the following also no error,

function f(i::Int64, weight::Array{Float64,2})
return nothing
end

But this is not what I want. I want the weight matrix in the argument have particular dimensions i by i.

Do I have to do things like

function f(i::Int64, weight::Array{Float64,2})
weight = Array{Float64,2}(undef,i,i)
return nothing
end

But again, I want the weight in the argument have the i by i definition. How to do that in Julia?

Thank you very much indeed!

1 Answers

Standard Array does not have its size as a part of type specification. If you want this feature use https://github.com/JuliaArrays/StaticArrays.jl instead.

However, most of the time it is just enough to write:

function f(i::Int, weight::Matrix{Float64})
    @assert size(weight) == (i, i)
end

This time the check is made within a function and not at method dispatch time, but typically this is enough.

If you strictly would require the the behavior you want at dispatch time then the method signature using https://github.com/JuliaArrays/StaticArrays.jl would be:

function f(i::Val{T}, weight::SMatrix{T, T, Float64}) where T::Int
end

Note that I need to wrap i in Val to make sure the number passed is available to the compiler and is not only a run-time value.

Related