In C, if you pass in a pointer to a function, the content of the involved variable may be changed. In Matlab, however, if you pass in an array as an argument, the content of the array will never be changed after the function call, even if the variable with the same name is modified within the function, unless the variable is also output. Ok, now comes the question: What if the function called by Matlab is written in C as a mex function? Haha, have fun with the following three tests, t1, t2, and t3.
/* File: t1.c */ #include
void foo(double *a) { a[0] = 1; }
void main(void) { double a[2] = {0}; foo(a); printf("first element of array a = %gn", a[0]); }
% File: t2.m function t2()
a = zeros(2,1); foo(a); fprintf(1, 'first element of array a = %gn', a(1));
function foo(a)
a(1) = 1;
% File: t3.m function t3()
a = zeros(2,1); foo_mex(a); fprintf(1, 'first element of array a = %gn', a(1));
Note: The copyright belongs to the blog author and the blog. For the license, please see the linked original source blog.
/* File: foo_mex.c */ #include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *a = mxGetPr(prhs[0]); a[0] = 1; }
Leave a Reply
You must be logged in to post a comment.