MATLAB: Mex file Fortran 77, create vector of size input argument

MATLABmex

I am trying to couple fortran 77 code with Matlab. The matlab input is a vector of an unknown size. To work with that vector in Fortran 77 I have to copy the vector to a fortran vector. What I cannot figure out is how to make the vector of size $n$ where $n$ is the size of the input vector of if need be a user supplied number.
I tried REAL*8 V(N), where N is later defined by N = mwSize(PRHS(-a number-)), but that did not compile.
Is this even possible?

Best Answer

Basic code outline with no error checking:
mwPointer, external :: mxGetPr
mwSize, external :: mxGetNumberOfElements
mwPointer pr
mwSize n
real*8, allocatable :: V(:)
:
pr = mxGetPr(prhs(1))
n = mxGetNumberOfElements(prhs(1))
allocate(V(n)) ! In your code you should error check this result
call mxCopyPtrToReal8(pr,V,n)
:
deallocate(V)
If you are only passing V to a subroutine and not working with it directly in mexFunction, you could also employ the %VAL( ) construct with pr to avoid making a copy of the input (i.e., avoids the use of the mxCopyPtrToReal8 routine).
You might also check this FEX submission which allows you to work with pointers to mxArray data areas instead of making data copies back & forth: