Alter values of variables in mexFunction from within a subfunction

조회 수: 9 (최근 30일)
Hello everyone,
I'm afraid this is a very basic question, but I couldn't find an answer to this, and I just don't get it working on my own:
I want to call a function minf.m via mexCallMATLAB within a subfunction minfcall, which is called from within a mexFunction. What I want to achieve is to alter the values of a and b by calling minfcall. When I run the code given below, the values of a and b displayed by mexPrintf from within minfcall are correct, but after exiting the function, the displayed values in mexFunction are the same as they were before calling minfcall.
Here's the code of the mexFunction:
#include "mex.h"
#include <string.h>
void minfcall(double *a, double *b){
mxArray *inp[1], *outp[2];
inp[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
memcpy(mxGetPr(inp[0]), a, sizeof(double));
mexPrintf("Before mexCallMATLAB:\n");
mexPrintf("a: %f\nb: %f\n", *a, *b);
mexCallMATLAB(2,outp,1,inp,"minf");
a = mxGetPr(outp[0]);
b = mxGetPr(outp[1]);
mexPrintf("After mexCallMATLAB:\n");
mexPrintf("a: %f\nb: %f\n", *a, *b);
}
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]){
double *a, *b;
a = mxGetPr(prhs[0]);
b = mxCalloc(1, sizeof(double));
minfcall(a, b);
mexPrintf("After exiting minfcall:\n");
mexPrintf("a: %f\nb: %f\n", *a, *b);
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
memcpy(mxGetPr(plhs[0]), a, sizeof(double));
plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);
memcpy(mxGetPr(plhs[1]), b, sizeof(double));
}
The m-File does the following:
function [a, b] = minf(a)
a = 2 * a;
b = 2 * a;
end
Can you tell me what I am doing wrong here?
Thank you very much for your support!

채택된 답변

Kaustubha Govind
Kaustubha Govind 2013년 8월 16일
You probably need to do this:
/* Copy the outputs of minf into a and b */
*a = *(mxGetPr(outp[0]));
*b = *(mxGetPr(outp[1]));
Instead of this:
/* Replace the pointer addresses of a and b with those of the output mxArrays */
a = mxGetPr(outp[0]);
b = mxGetPr(outp[1]);
Also, remember to destroy the output mxArrays at the end of minfcall so you're not leaking memory:
mxDestroyArray(outp[0]);
mxDestroyArray(outp[1]);
  댓글 수: 2
James Tursa
James Tursa 2013년 8월 18일
And also the input mxArray:
mxDestroyArray(inp[0]);
Adrian Buerger
Adrian Buerger 2013년 8월 19일
Thank you people very much! Of course, this solved my problem (which as I already thought really was a beginner's mistake)!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by