首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >梅克斯:计算正确;但是,我的输出是错误的。

梅克斯:计算正确;但是,我的输出是错误的。
EN

Stack Overflow用户
提问于 2015-04-08 22:47:02
回答 1查看 74关注 0票数 1

我正在尝试使用mex来调用Matlab中的c-函数.

似乎我可以得到正确的输入,甚至计算都是正确的。但是,它返回错误的输入。不知何故,我搞砸了输出指针,请帮忙。

Matlab代码:

代码语言:javascript
复制
cd /home/dkumar/MatlabCodes_DKU;
smA_System = ConstructSystemMatrix();

Dir2  = '/home/dkumar/Mex_Codes_DKU/MexCode_Working/Mex_C_Codes_DKU_makefile_Working';

% MEX
cd(Dir2);
system('make');
tic
    y = normpdfDKU(1/2,0,1)
toc

C码

代码语言:javascript
复制
#include "mex.h"
#include <math.h>
#include <stdio.h>

/* using namespace std; */

#define pi (3.141592653589793)

extern void _main();

const int numInputArgs  = 3;
const int numOutputArgs = 1;

// Function declarations.
// -----------------------------------------------------------------
double  getMatlabScalar    (const mxArray* ptr);
//double& createMatlabScalar (mxArray*& ptr);

// Function definitions.
// -----------------------------------------------------------------
void mexFunction (int nlhs, mxArray *plhs[],
          int nrhs, const mxArray *prhs[]) {


  int res = TestingLibraries() ; 

  //declare variables
  mxArray *c_out_m;
  double  *c, p, c1;

  #define B_OUT plhs[0]

  // Check to see if we have the correct number of input and output
  // arguments.
  if (nrhs != numInputArgs)
    mexErrMsgTxt(" DKU-1: Incorrect number of input arguments");
  if (nlhs != numOutputArgs)
    mexErrMsgTxt("DKU-2: Incorrect number of output arguments");

  // Get the inputs.
  double x  = getMatlabScalar(prhs[0]);
  double mu = getMatlabScalar(prhs[1]);
  double v  = getMatlabScalar(prhs[2]);

  // Create the output. It is also a double-precision scalar.
  //double& p = createMatlabScalar(plhs[0]);

  //associate outputs
  plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
  //associate pointers
  c = mxGetPr(plhs[0]);

  // Compute the value of the univariate Normal at x.
  p = (double)(exp(-(x-mu)*(x-mu)/(2*v)) / sqrt(2*pi*v));
  printf("First normal value: %f\n", p);

  c = &p; 
}

double getMatlabScalar (const mxArray* ptr) {

  // Make sure the input argument is a scalar in double-precision.
  if (!mxIsDouble(ptr) || mxGetNumberOfElements(ptr) != 1)
    mexErrMsgTxt("The input argument must be a double-precision scalar");

  return *mxGetPr(ptr);
}

输出:

代码语言:javascript
复制
First normal value: 0.352065

y =

     0

Elapsed time is 0.002202 seconds.
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-08 22:59:05

问题就在这里

代码语言:javascript
复制
c = &p;

您正在重新定位指针c,以便它现在指向p的地址。

您要做的是将p的内容复制到c当前指向的地址(您以前创建的标量的真实部分)。

代码语言:javascript
复制
*c = p;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29526646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档