C++ 更改mex函数中的常量参数
这个问题是我正在进行的一个更大项目的一部分。我使用了一个更简单的mex函数来解释我正在处理的问题 要求是更改传递给mex函数的参数(RHS上的变量)。这是一项必要的要求。 我已经能够在double*as argumjents的情况下更改变量。代码如下:C++ 更改mex函数中的常量参数,c++,c,matlab,mex,C++,C,Matlab,Mex,这个问题是我正在进行的一个更大项目的一部分。我使用了一个更简单的mex函数来解释我正在处理的问题 要求是更改传递给mex函数的参数(RHS上的变量)。这是一项必要的要求。 我已经能够在double*as argumjents的情况下更改变量。代码如下: #include "mex.h" /* The computational routine */ void arrayProduct(double x, double *y, double *z, mwSize n)
#include "mex.h"
/* The computational routine */
void arrayProduct(double x, double *y, double *z, mwSize n)
{
mwSize i;
/* multiply each element y by x */
for (i=0; i<n; i++) {
z[i] = (x * y[i]);
}
}
/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
double multiplier; /* input scalar */
double *inMatrix; /* 1xN input matrix */
size_t ncols; /* size of matrix */
double *outMatrix; /* output matrix */
/* check for proper number of arguments */
if(nrhs!=3) {
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs","Three inputs required.");
}
if(nlhs!=0) {
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs","Zero output required.");
}
/* get the value of the scalar input */
multiplier = mxGetScalar(prhs[0]);
/* create a pointer to the real data in the input matrix */
inMatrix = mxGetPr(prhs[1]);
/* get dimensions of the input matrix */
ncols = mxGetN(prhs[1]);
/* get a pointer to the real data in the output matrix */
outMatrix = mxGetPr(prhs[2]);
/* call the computational routine */
arrayProduct(multiplier,inMatrix,outMatrix,(mwSize)ncols);
}
#包括“mex.h”
/*计算程序*/
空阵列产品(双x、双y、双z、MWN)
{
MWi尺寸;
/*将每个元素y乘以x*/
对于(i=0;i将指针投射到其他类型不会将其指向的数据转换为该类型。几乎所有Matlab数据都是double
数组。如果函数需要int
数组,则需要为int
分配一个单独的数组,并一次转换一个元素。是的,但它会失败使用mex函数来提高速度的通常目的..注意:明确禁止更改mex文件中的RHS参数。由于MATLAB的延迟复制,也可能导致其他矩阵的意外更改。声明这些数组为const
,这是有原因的!
/* The computational routine */
void arrayProduct(double x, double *y, int *z, mwSize n)
{
mwSize i;
/* multiply each element y by x */
for (i=0; i<n; i++) {
z[i] = (x * y[i]);
}
}
/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
double multiplier; /* input scalar */
double *inMatrix; /* 1xN input matrix */
size_t ncols; /* size of matrix */
int *outMatrix; /* output matrix */
/* check for proper number of arguments */
if(nrhs!=3) {
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs","Two inputs required.");
}
if(nlhs!=0) {
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs","One output required.");
}
/* get the value of the scalar input */
multiplier = mxGetScalar(prhs[0]);
int mult = (int)multiplier;
/* create a pointer to the real data in the input matrix */
inMatrix = mxGetPr(prhs[1]);
/* int *inMat;
inMat = *inMatrix;*/
/* get dimensions of the input matrix */
ncols = mxGetN(prhs[1]);
/* create the output matrix */
/* get a pointer to the real data in the output matrix */
outMatrix = (int *)mxGetData(prhs[2]);
/* call the computational routine */
arrayProduct(multiplier,inMatrix,outMatrix,(mwSize)ncols);
}