Basic question about pointer in mex function
古いコメントを表示
Hello,
I am getting confused with the basic concept of pointer in mex function. So I have couple of questions...
Below is an example from mathwork.
Q1.
As far as I know, in C++, when we declare double *y for the first time, y is the variable that stores address for data type double.
void arrayProduct(double x, double *y, double *z, mwSize n)
z[i] = x * y[i];
But I was wondering if z, y stores addresses not values how can we calculate like this z[i] = x * y[i]; ?
Shouldn't this be something like (*z)[i] and (*y)[i]? but then I see the message
error: subscripted value is neither array nor pointer nor vector
(*z)[i] = x * (*y)[i];
So I guess y stores the value.
Q2.
In the gateway function,
double *inMatrix; inMatrix is supposed to be a variable that stores addresses of data type double
inMatrix = mxGetPr(prhs[1]); inMatrix stores addresses of second argument of the input variable
Am I understanding this concept correctly?
Q3.
Then, 'inMatrix' is a pointer to 'A'
`y' is a pointer to 'inMatrix'
'multiplier' is a copy of 's'
'x' is a copy of 'multiplier'
Any help would be appreciated.
Thanks in advance.
#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 */
/* 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]);
/* create the output matrix */
plhs[0] = mxCreateDoubleMatrix(1,(mwSize)ncols,mxREAL);
/* get a pointer to the real data in the output matrix */
outMatrix = mxGetPr(plhs[0]);
/* call the computational routine */
arrayProduct(multiplier,inMatrix,outMatrix,(mwSize)ncols);
}
clc
clear all;
clear mex;
mex arrayProduct.c
s = 5;
A = [1.5, 2, 9];
B = arrayProduct(s,A)
1 件のコメント
James Tursa
2021 年 2 月 17 日
Probably the thing to do is brush up on C/C++ pointers. Maybe look through some online tutorials. E.g.,
double *z
means
z is of type "pointer to double"
z[i] is of type "double"
*z is of type "double"
and
(*z)[i]
makes no sense because you can't deference a double ... you can only dereference pointers to something.
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Write C Functions Callable from MATLAB (MEX Files) についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!