开发者

Run Matlab mex-Algorithm instead of Double- in Single-Precision

开发者 https://www.devze.com 2023-03-15 05:19 出处:网络
I have a working Matlab C code (mex files) which currently uses double precision. Thus I replaced double *datOut = mxGetPr(mxOut) by float *datOut = (float*)mxGetData(mxOut);,

I have a working Matlab C code (mex files) which currently uses double precision. Thus I replaced

double *datOut = mxGetPr(mxOut) by float *datOut = (float*)mxGetData(mxOut);,

mxCreateDoubleMatrix by mxCreateNumericArray()

and

the datatypes of the variables double by float. The only other mex-Function which is being used is mxDuplicateArray() but nothing else. I didn't change anything to this call... Now I have a Code running which never finishes. I stripped it down quite a bit so that I hope it's short enough that somebody could help me:

float myFunc(const mxArray *point, int index)
{
    float *dat = (float*)mxGetData(point);
    return dat[index]*dat[index]*dat[index];
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const开发者_如何学运维 mxArray *prhs[] )
{
    float h, f0, df1, df2, diff;

    // Input Vars #1
    float diff  = (float)mxGetScalar(prhs[1]);
    float H = (float)mxGetScalar(prhs[2]);
    int index1 = (int)mxGetScalar(prhs[3]);
    int index2 = (int)mxGetScalar(prhs[4]);

    // Input Vars #2 -> Duplicate it
    mxArray *newPnt = mxDuplicateArray(prhs[0]);
    float *newPntDat = (float*)mxGetData(newPnt);

    // ...
    // PERHAPS SOME UNIMPORANT CODE HERE ...
    // ...
    h = H;
    f0 = myFunc(prhs[0], index1);

    newPntData[ index2 ] += h;
    df1 = (myFunc(newPnt, index1)-f0)/h;
    while(true)
    {
        h /= 2;

        newPntDat[ index2 ] -= h;
        df2 = (myFunc(newPnt, index1)-f0)/h;

        // If precision is okay
        if(abs(df2-df1) <= diff)
            break;

        // Save for next loop iteration
        df1 = df2;
    }

    // Return df2-Value to Matlab
}

somehow it's an infinite loop and I dunno why since the precision which is defined via diff should be easily reachable for the given function myFunc(). The identicall code runs fine when using double precision with the both functions double *datOut = mxGetPr(mxOut) and mxCreateDoubleMatrix. I also tried to call the mex-Function by explicitly pass the point via point = zeros(rows, 1, 'single');.

Thanks very much for pointing me to the right direction or giving me ANY hint about it. Thanks!


You need to replace abs() with fabs().

In general, in such cases, I would use mexPrintf() to print the values that affect the termination condition. I.e., if the above change does not help, try adding

mexPrintf("%g %g %g %g\n",df2,df1,diff, fabs(df2-df1));

Just to make sure the behavior is as you expected.

0

精彩评论

暂无评论...
验证码 换一张
取 消