Search code examples
matlabvariablesexeworkspacemex

How to run .exe programs passing variables from Matlab workspace?


I 'm working on a Matlab project that requires large data processing and some parts of the code need to run faster than Matlab functions. For this purpose I need to call an .exe inside other scripts passing variables from the workspace. In order to understand how I could solve that a created a small addition program.

I have the following code

function test(a,b)
if ischar(a)
  a2=str2num(a);
else
  a2=a;
end
if ischar(b)
  b2=str2num(b);
else
  b2=b;
end
res=a2+b2;
disp(res)

and I used the deployment tool in order to make it executable. If I run the test.exe through matlab with !test.exe 5 3 it works, If I create two variables a=5 and b=3 and try !test.exe a b it doesn't work.

I know that I can pass the variables to a .txt or .dat file and then close and re opened again through the program (the variables that I need to use are dynamic) but I don't believe that its more efficient than running mfile loading variables from workspace.

I also searched about the use varargin,nargin etc. but these commands don't have the use of argc[], argv[] of C. Something like that it could solve my issues.

Then I search for mex files and write the following code:

#include "mex.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
   mxArray *mexGetVariable(const char *workspace, const char *varname);

   const mxArray *mex_a;
   const mxArray *mex_b;

   //http://www.mathworks.com/help/techdoc/apiref/mexgetvariable.html
   if ((mex_a = mexGetVariable("a", "global"))==NULL)
   {
        mexErrMsgTxt("Variable 'a' not in workspace.");
   }
   else if ((mex_b = mexGetVariable("b", "global"))==NULL)
   {
        mexErrMsgTxt("Variable 'b' not in workspace.");
   }
   else
   {
        mexEvalString("!test.exe mex_a mex_b"); 
   }
} 

(I have also passed variable a=5 b=3) But nothing worked as I have a prompt saying Variable a not in the workspace.

Can anyone provide me a code solution on how can I make .exe programs reading variables from matlab workspace without opening .txt or .dat files?

Thank you in advance for your kindness in reading my topic.


Solution

  • The command !test.exe a b is trying to run test.exe on the strings 'a' and 'b', not the values of a and b. This would be the case whether you ran it from the command line or via a mex file.

    If you do something like:

    >> a=5; b=3;
    >> cmdstr = sprintf('!test.exe %f %f',a,b)
    cmdstr =
    !test.exe 5.000000 3.000000
    >> eval(cmdstr)
    

    That would call it in the way I think you're intending.

    Is your real .exe (not the test.exe) created from MATLAB with MATLAB Compiler? If so, the above still may not achieve what you're looking for. Executables created using MATLAB Compiler run at the same speed as live MATLAB.