Save state in Matlab function called from c# -


i´m trying call matlab function c# , not problem, problem need keep state in matlab part in order use previous results in next calculation. state should exist in matlab runtime.

enter image description here

i have tried use globals without luck in c#, , guess that´s not pretty solution @ or it?

i tried getmcruserdata/setmcruserdata can make work in matlab not in c#.

i hope has input or better examples.

update

i tried following approaches

classdef mablab classes don´t seem work in .net

global variable (did not work)

function y = statecalc1(x)  global state state = state + x;  y = state; 

persistent (did not work)

function y = statepersistent(x)  persistent state state = state + x;  y = state; 

getmcruserdata/setmcruserdata (worked)

function y = statecalc2(x)  val = getmcruserdata('data');  if (isempty(val))     val = x; else     val = val + x;     end  setmcruserdata('data',val);  y = val; 

this actually works now, still don´t know if it´s best approach?

.net/c#

  var testclass = new testclass();    (int = 0; < 10; i++)   {     mwarray input = i;     result = testclass.statecalc(input);      var output = (mwarray)result;     console.writeline(output);   }    console.readkey(); 

i assume you're using matlab compiler sdk create matlab component here (or matlab builder .net known in older versions of matlab).

if so, it's designed deploying functionality not require state - typically deploy things purely function-based interface. if have store state, it's better if can on .net side.

you can use persistent variables store state between function calls, need careful, variable remain persistent while mcr stays up. if call .net makes mcr start up, carries out function call, , shuts mcr down, variable not remain persistent across calls.

if need ensure mcr remains up, can write small .net wrapper application nothing start mcr, , pass through calls main application (and shuts down on exit). may need worry explicitly monitoring mcr in case cause crash (for example causing run out of memory), , if so, bringing up.

before start down route, though, take @ matlab production server. add-on product designed address of issues you'll end facing, such managing pool of mcrs - lot more, though, , relatively expensive, may overkill application.

alternatively, can store state writing , reading file between function calls - may slow, though, depending on size of state.


Comments