Error in using mldivide in mex

1 view (last 30 days)
srinadh
srinadh on 20 Jul 2014
Edited: James Tursa on 20 Jul 2014
I am trying to use mldivide inside mex. The below code is simply trying to solve Ax=b, for r=5, where A is 5*5 Identity and b=0:1:4. So mldivide should output x=0:1:4. Instead I am getting all 0's as output vector. Can anyone see the mistake in the code?
Thanks
A=lsm, b=lsv and x=lss in the code below.
#include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mwIndex l, k;
double *lsm, *lsv, *lss;
mxArray *Lsmatrix[2];
int r;
r=*((double *)mxGetPr(prhs[0]));
plhs[0]=mxCreateDoubleMatrix(r, 1, mxREAL);
lss=mxGetPr(plhs[0]);
Lsmatrix[0]=mxCreateDoubleMatrix(r, r, mxREAL);
Lsmatrix[1]=mxCreateDoubleMatrix(r, 1, mxREAL);
lsm=mxGetPr(Lsmatrix[0]);
lsv=mxGetPr(Lsmatrix[1]);
for(l=0; l<r;l++){
for(k=0;k<r;k++){
lsm[k+l*r]=0;
if(l==k){
lsm[k+l*r]=1;
}
}
lsv[l]=l;
}
mexCallMATLAB(1, lss, 2, &Lsmatrix , "mldivide");
}

Accepted Answer

James Tursa
James Tursa on 20 Jul 2014
Edited: James Tursa on 20 Jul 2014
You don't need to create plhs[0] explicitly since the mexCallMATLAB call will do that for you. Also, you don't need to explicitly fill in the 0's in the off diagonals of the r x r matrix since mxCreateDoubleMatrix will automatically do that for you as well. And you don't need to cast the result of mxGetPr with a (double *) since that is the return type of the function ... also a simpler way of doing this is mxGetScalar anyway. Finally, you can't pass a (double *) to mexCallMATLAB as the 2nd argument ... it is expecting an array of (mxArray *) type. And you don't need to explicitly pass the "address of" the array as the 4th argument, you can just pass the array name. So, e.g.,
#include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mwIndex k;
double *lsm, *lsv;
mxArray *Lsmatrix[2];
int r;
r = mxGetScalar(prhs[0]);
Lsmatrix[0] = mxCreateDoubleMatrix(r, r, mxREAL);
Lsmatrix[1] = mxCreateDoubleMatrix(r, 1, mxREAL);
lsm = mxGetPr(Lsmatrix[0]);
lsv = mxGetPr(Lsmatrix[1]);
for(k=0; k<r; k++){
*lsm = 1.0;
lsm += r+1;
lsv[k] = k;
}
mexCallMATLAB(1, plhs, 2, Lsmatrix , "mldivide");
mxDestroyArray(Lsmatrix[1]);
mxDestroyArray(Lsmatrix[0]);
}
  3 Comments
James Tursa
James Tursa on 20 Jul 2014
Edited: James Tursa on 20 Jul 2014
Did you copy and paste the entire function exactly as I have written it? How are you calling the function? Here is what I get:
>> mldivide_example(5)
ans =
0
1
2
3
4
srinadh
srinadh on 20 Jul 2014
Sorry, I was compiling the wrong file. It works great now. Thanks.

Sign in to comment.

More Answers (0)

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!