pass a vector from matlab to a c++ program

9 ビュー (過去 30 日間)
SA-W
SA-W 2022 年 8 月 13 日
コメント済み: Torsten 2022 年 8 月 14 日
function res = fun(p,y)
s = call_a_cpp_program_which_operates_on_p
res = s - y;
end
In the above function, 'p' is a vector and 's' as well. I have to pass the vector 'p' to a c++ program to compute 's'. The above function is called several times.
My idea is to first write the vector 'p' in a file, which the c++ program reads in. The c++ program writes its output 's' also in a file, which MATLAB can read in.
Probably this would work, but is there a better approach to transfer the vector 'p' from MATLAB to my c++ program?
  9 件のコメント
SA-W
SA-W 2022 年 8 月 14 日
I guess the system command is exactly what I need as for the communication between the processes. In the documentation, it says that MATLAB waits for the executed command to be finished, i.e., until my pde solver exits.
But maybe James wants to add another comment below.
Torsten
Torsten 2022 年 8 月 14 日
In such cases I always say:
The proof of the pudding is in the eating (Probieren geht über Studieren).

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

採用された回答

James Tursa
James Tursa 2022 年 8 月 14 日
編集済み: James Tursa 2022 年 8 月 14 日
This really depends on what your C++ program does, but the simplest approach is to use a mex routine. You will need a supported C++ compiler installed. An example of a bare bones (i.e., no argument checking) C++ mex routine is as follows:
// File mymex.cpp
// Y = mymex(X)
// where X = a full double variable
// Y = 2.0 * X
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mwSize i, n;
double *p;
plhs[0] = mxDuplicateArray(prhs[0]); // Create the output variable as a deep copy of input
n = mxGetNumberOfElements(prhs[0]); // Number of elements of input variable
p = (double *) mxGetData(prhs[0]); // Pointer to output variable data
for( i=0; i<n; i++ ) {
p[i] *= 2.0; // Multiply the output elements by 2.0
}
}
Save this file under the name mymex.cpp, then compile it with the mex command:
mex mymex.cpp
This routine simply returns the input variable multiplied by 2. E.g.,
x = 1:5;
y = mymex(x)
Another approach is to have your C++ code compiled as a library, and then use the loadlibrary( ) and calllib( ) functionality to call the C++ routine.
  1 件のコメント
SA-W
SA-W 2022 年 8 月 14 日
Thanks for your answer James. I think I can make it with your suggestions to pass the vector.
Given the discussion with Torsten in the comments above, can you help regarding the communication between MATLAB and my c++ program?

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeC Shared Library Integration についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by