フィルターのクリア

calling matlab from c++

3 ビュー (過去 30 日間)
naman
naman 2015 年 10 月 12 日
コメント済み: James Tursa 2018 年 3 月 19 日
Hi
I am trying to print values obtained from matlab function which is called in c++ program. This is the code, I am not sure how can I print values.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "engine.h"
int main()
{
Engine *ep;
if (!(ep = engOpen(""))) {
fprintf(stderr, "\nCan't start MATLAB engine\n");
return EXIT_FAILURE;
}
int const SIZE=1;
int const SIZE2=1;
double x[SIZE][SIZE2];
x[1][1] = 1.0;
mxArray *A=NULL;
A=mxCreateDoubleMatrix(SIZE2, SIZE, mxREAL);
memcpy((void *)mxGetPr(A), (void *)x, sizeof(double)*SIZE*SIZE2);
engPutVariable(ep, "Data", A);
engEvalString(ep, "newData = test_matlab(Data)");
double *cresult;
mxArray *mresult;
mresult = engGetVariable(ep,"newData");
cresult = mxGetPr(mresult);
mxDestroyArray(A);
mxDestroyArray(mresult);
engClose(ep);
return EXIT_SUCCESS;
}

採用された回答

James Tursa
James Tursa 2015 年 10 月 12 日
編集済み: James Tursa 2015 年 10 月 12 日
Use regular output functions. E.g., ( after you assign the value of cresult but before you destroy the mxArray mresult ):
printf( "The result is %g\n", *cresult );
But note that you will need to pause your program at the end in order to see this output on the screen (otherwise the window will close immediately after printing and you will not see it).
SIDE NOTE:
All of this code:
int const SIZE=1;
int const SIZE2=1;
double x[SIZE][SIZE2];
x[1][1] = 1.0;
mxArray *A=NULL;
A=mxCreateDoubleMatrix(SIZE2, SIZE, mxREAL);
memcpy((void *)mxGetPr(A), (void *)x, sizeof(double)*SIZE*SIZE2);
can be simplified to this:
mxArray *A=NULL;
A = mxCreateDoubleScalar(1.0);
Also, you should be getting in the habit of checking your pointers before using them. E.g., A, mresult, and cresult should all be checked to see that they are not NULL before you try to dereference them.

その他の回答 (1 件)

HANS
HANS 2018 年 3 月 19 日
Hi to all,
I have name.mex function and many .cpp and .h files related to it. name.mex takes only 1xinf vector which is a complex double values inside and output is the same size vector.
I want to call this name.mex within C++. As I know I have to use "int mexCallMATLAB(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[], const char *command_name);"
Please could you give a usage example in C++ ? I guess I have to use "ifstream" to load the data vector before I use the function but do I have to define via "mxArray" or ??
Thx, WR
  1 件のコメント
James Tursa
James Tursa 2018 年 3 月 19 日
Please open up a new Question on this topic, and if possible post the relevant code so we can advise you.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeWrite 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!

Translated by