Calling from Matlab a recusive function written in C
Mostrar comentarios más antiguos
Hi,
I have a written a recursive function in C to replace nchoosek() in Matlab. When i call this function in Matlab, it gives error if i use output parameter. If i don't use output parameter then it does not return the required answer. I have tried to debug it but of no use.
Code without output parameter is:
#include "math.h"
#include "mex.h"
double test(double n, double k)
{
if (k ==0){
return 1;
}
else
{
return(n*test(n-1,k-1))/k;
}
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,
const mxArray *prhs[])
{
double y, n, k;
/* Create matrix for the return argument. */
plhs[0] = mxCreateDoubleMatrix(1,1, mxREAL);
/* Assign pointers to each input and output. */
n = mxGetScalar(prhs[0]);
k = mxGetScalar(prhs[1]);
/* Call the test subroutine. */
test(n,k);
}
Code with output parameter is:
#include "math.h"
#include "mex.h"
double test(double *y, double n, double k)
{
if (k ==0){
return 1;
}
else
{
*y=(n*test(n-1,k-1))/k;
}
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,const mxArray *prhs[])
{
double *y, n, k;
/* Create matrix for the return argument. */
plhs[0] = mxCreateDoubleMatrix(1,1, mxREAL);
/* Assign pointers to each input and output. */
n = mxGetScalar(prhs[0]);
k = mxGetScalar(prhs[1]);
y = mxGetPr(plhs[0]);
/* Call the test subroutine. */
test(y,n,k);
}
I have to implement this function since nchoosek(n,k) gives warning if i compute it for higher values of n & k.
I will be highly obliged if any one is kind enough to help me out.
Ameer
Respuesta aceptada
Más respuestas (2)
Geoff Hayes
el 14 de Jun. de 2017
Ameer - you are getting an error with the output parameter code because of your recursive call to test
*y=(n*test(n-1,k-1))/k;
So two parameters are being passed in to test but three are required
double test(double *y, double n, double k)
so you will need to either pass in the third parameter to test or re-work this method in order to return a value instead of updating the input y
double test(double n, double k)
{
if (k == 0)
{
return 1;
}
else
{
return (n*test(n-1,k-1))/k;
}
}
Note also that you will want to re-think how you are calculating n choose k. Remember, that this is really
n!/((n-k)!*(k!))
rather than the
n!/k!
that you seem to have.
2 comentarios
James Tursa
el 15 de Jun. de 2017
test(n,k) =
n! / ( (n-k)! * (k!) ) =
n * (n-1)! / ( (n-k)! * k * (k-1)! ) =
n * (n-1)! / ( ( (n-1) - (k-1) )! * (k-1)! ) / k =
n * test(n-1,k-1) / k
So the recursive call in the above code appears to be correct.
Geoff Hayes
el 15 de Jun. de 2017
hmmm...I was getting a different answer when comparing it with the MATLAB nchoosek. But now I'm not - weird!
Ameer Ahmed
el 15 de Jun. de 2017
Categorías
Más información sobre C MEX 文件应用程序 en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!