[R] Use of .Fortran
Duncan Murdoch
murdoch.duncan at gmail.com
Fri Jun 18 16:58:55 CEST 2010
On 18/06/2010 9:59 AM, David Scott wrote:
> I have no experience with incorporating Fortran code and am probably
> doing something pretty stupid.
>
> I want to use the following Fortran subroutine (not written by me) in
> the file SSFcoef.f
>
> subroutine SSFcoef(nmax,nu,A,nrowA,ncolA)
> implicit double precision(a-h,o-z)
> implicit integer (i-n)
> integer l,i,nmax
> double precision nu,A(0:nmax,0:nmax)
> A(0,0) = 1D0
> do l=1,nmax
> do i=1,l-1
> A(l,i) = (-nu+i+l-1D0)*A(l-1,i)+A(l-1,i-1)
> end do
> A(l,0) = (-nu+l-1D0)*A(l-1,0)
> A(l,l) = 1D0
> end do
> return
> end
>
>
> I created a dll (this is windows) using R CMD SHLIB SSFcoef.f
>
> Then my R code is:
>
> ### Load the compiled shared library in.
> dyn.load("SSFcoef.dll")
>
> ### Write a function that calls the Fortran subroutine
> SSFcoef <- function(nmax, nu){
> .Fortran("SSFcoef",
> as.integer(nmax),
> as.integer(nu)
> )$A
> }
>
> SSFcoef(10,2)
>
> which when run gives
>
> > SSFcoef(10,2)
> NULL
>
> I am pretty sure the problem is that I am not dealing with the matrix A
> properly. I also tried this on linux and got a segfault.
>
> Can anyone supply the appropriate modification to my call (and possibly
> to the subroutine) to make this work?
Two problems:
Your subroutine takes 5 arguments, you're only passing two.
You didn't name your arguments, but are trying to retrieve A by name.
So this will get you closer (it's untested, so there might still be
problems...):
SSFcoef <- function(nmax, nu){
.Fortran("SSFcoef",
as.integer(nmax),
as.integer(nu),
A = numeric((nmax+1)^2),
nrowA = as.integer(nmax+1), # These are unused...
ncolA = as.integer(nmax+1)
)$A
}
Duncan Murdoch
More information about the R-help
mailing list