问题
I'm trying to solve a linear system with DGESV in a mex file. When I have a 2x2 system, the mex file works fine and no errors occurred, but when the system is larger than 2, MATLAB System Error dialog box apperas and says that matlab has encountered an internal problem and needs to be closed. Im using matlab r2016a on 64-bit windows 10 and intel composer XE 2013
The compile line is:
mex -lmwlapack *.F
The code is as follows:
#include "fintrf.h"
C Gateway subroutine
subroutine mexfunction(nlhs, plhs, nrhs, prhs)
C Declarations
implicit none
C mexFunction arguments:
mwPointer plhs(*), prhs(*)
integer nlhs, nrhs
C Function declarations:
mwPointer mxGetPr
mwPointer mxCreateDoubleMatrix
mwPointer mxGetM
C Pointers to input/output mxArrays:
mwPointer pr_A, pr_B, pr_C
C Array information:
mwPointer sizea
real*8 , allocatable :: A(:,:)
+ ,B(:,:),C(:,:)
C Get the size of the input array.
sizea = mxGetM(prhs(1))
allocate(A(sizea,sizea),B(sizea,1))
allocate(C(sizea,1))
C Create Fortran array from the input argument.
pr_A = mxGetPr(prhs(1))
pr_B = mxGetPr(prhs(2))
call mxCopyPtrToReal8(pr_A,A,sizea**2)
call mxCopyPtrToReal8(pr_B,B,sizea)
C Create matrix for the return argument.
plhs(1) = mxCreateDoubleMatrix(sizea, 1, 0)
pr_C = mxGetPr(plhs(1))
C Call the computational routine.
Call SolveLS(A,B,C,sizea)
call mxCopyReal8ToPtr(C,pr_C,sizea)
return
end
C Computational routine
subroutine SolveLS(A,B,C,sizea)
integer*4 :: sizea,pivot(sizea),info
real*8 :: A(sizea,sizea),B(sizea,1), C(sizea,1)
call DGESV(sizea, 1,A,sizea,pivot,B,sizea,info)
C=B
return
end subroutine SolveLS
回答1:
A system error like this normally indicates that you've corrupted the memory with a bad memory allocation. I notice you are using the standard Fortran allocate function instead of mxMalloc which allows MATLAB to handle the memory allocation and deallocation. Note that mxMalloc'ed memory is automatically destroyed at the end of the MEX function call, but you can use mxFree to free it up.
Information on mxMalloc can be found in the Matlab help files
来源:https://stackoverflow.com/questions/39509572/error-using-dgesv-in-matlab-mex