3

Are there any ways to run a Matlab script (without function) in C# Windows Application? I would like my Matlab script to run when I click on a button in my C# form. I tried the Matlab Compiler to build my script and obtained the dll and also using private MLApp.MLAppClass Matlab; But I'm not too sure how to get it running and the code in the button function.

Any help would be much appreciated. Thank you.

using testNN;
public partial class Form1 : Form
{
    private testNN.Class1 matlab;

    public Form1()
    {
        InitializeComponent();

    }

private void button1_Click(object sender, EventArgs e)
{

        try
        {
            matlab = new testNN.Class1();
            matlab.resourceforecast();
        }
         catch (Exception ex)
        { MessageBox.Show(ex.Message); }
}
Ping
  • 41
  • 3
  • Using the MATLAB Compiler is indeed the way to go. Can you give more details about what you don't understand about it? – dee-see Feb 18 '14 at 16:42
  • There is also the matlab command line. If your C# can give input to a command-line then MatLab can take it from there. http://stackoverflow.com/questions/6657005/matlab-running-an-m-file-from-command-line – EngrStudent Feb 18 '14 at 16:48
  • After I have obtained the dll from the Matlab compiler, I add it to the C# reference. However, I'm not too sure how to proceed from there. How should I go about using the dll to code in C#? – Ping Feb 18 '14 at 16:51
  • @Ping Just like any other reference, you create an instance of the class you created with the compiler and call its methods. Try something and if it does not work post some code so we can help a bit more. – dee-see Feb 18 '14 at 17:09
  • I have tried and got an error: The type initializer for 'testNN.Class1' threw an exception. The code I have written have been included in my question. How do I solve this problem? Thank you! – Ping Feb 19 '14 at 10:18
  • I provided some sample code [here](http://stackoverflow.com/a/18727012/885844) - this is for calling an exe (for cmd use), but using an assembly things are even simpler (you use it as any other assembly). Perhaps this is of some help to you? – w128 Feb 19 '14 at 10:26

1 Answers1

0

The easiest would be to use the COM approach.

See here for the COM approach and other approaches as well.

An example, inspired by the above reference:

m = CreateObject("Matlab.Application")
m.Execute("script_name");

As a side note, when googling for questions in C#, it is usually more efficient to look for the issue with .NET instead (e.g. "matlab .net integration" ). The answer then could be easily applied across all .NET enviroments.

Yuval Atzmon
  • 5,645
  • 3
  • 41
  • 74