title: Save state in Matlab function called from c#
body: <p>I´m trying to call a Matlab function from C# and that is not really a problem, the problem is that I need to keep state in the Matlab part in order to use the previous results in the next calculation. This state should only exist in the Matlab runtime.</p>
  
  <p><img src="https://i.stack.imgur.com/2rxGp.png" alt="enter image description here"></p>
  
  <p>I have tried to use globals without any luck in C#, and I guess that´s not a pretty solution at all or is it?</p>
  
  <p>I also tried getmcruserdata/setmcruserdata but I can only make that work in Matlab not in C#.</p>
  
  <p>I hope that someone has some input or even better some examples.</p>
  
  <h2>Update</h2>
  
  <p>I tried the following approaches </p>
  
  <p><strong>classdef</strong>
  But MabLab classes don´t seem to work in .Net</p>
  
  <p><strong>global variable</strong> (Did not work)</p>
  
  <pre><code>function y = stateCalc1(x)
  
  global state
  state = state + x;
  
  y = state;
  </code></pre>
  
  <p><strong>persistent</strong> (Did not work)</p>
  
  <pre><code>function y = statePersistent(x)
  
  persistent state
  state = state + x;
  
  y = state;
  </code></pre>
  
  <p><strong>getmcruserdata/setmcruserdata</strong> (Worked)</p>
  
  <pre><code>function y = stateCalc2(x)
  
  val = getmcruserdata('data');
  
  if (isempty(val))
      val = x;
  else
      val = val + x;    
  end
  
  setmcruserdata('data',val);
  
  y = val;
  </code></pre>
  
  <p>This <strong>actually works</strong> now, but I still don´t know if it´s the best approach? </p>
  
  <p><strong>.Net/C#</strong></p>
  
  <pre><code>  var testClass = new TestClass();
  
    for (int i = 0; i &lt; 10; i++)
    {
      MWArray input = i;
      result = testClass.stateCalc(input);
  
      var output = (MWArray)result;
      Console.WriteLine(output);
    }
  
    Console.ReadKey();
  </code></pre>