## Execute MATLAB Functions from .NET

When you call a MATLAB® function from .NET, you can pass .NET variables to the function. If the MATLAB function returns an output variable, the engine converts it from MATLAB to .NET.

For information on how to set up and build .NET engine programs, see Test Your .NET Development Environment.

### Pass Variables from .NET to MATLAB

In this example, you create a 1-D double array using the MATLAB `linspace` function and reshape the elements using `reshape`. For information about converting data from .NET to MATLAB, see Pass .NET Data Types to MATLAB Functions.

The MATLAB code for this example is:

```A = linspace(-5.0,5.0); sz = [25,4]; B = reshape(A,sz);```

The C# code for this example is:

```using MathWorks.MATLAB.Engine; using MathWorks.MATLAB.Exceptions; using MathWorks.MATLAB.Types; using System; namespace MathWorks.MATLAB.Engine.ConsoleExamples { public class Program { public static void Main(string[] args) { Console.Write("Starting MATLAB... "); using (dynamic matlab = MATLABEngine.StartMATLAB()) { Console.WriteLine("done."); double[] A = matlab.linspace(-5.0,5.0); int[] sz = new int[] {25,4}; double[,] B = matlab.reshape(A,sz); } // Call when you no longer need MATLAB Engine in your application. MATLABEngine.TerminateEngineClient(); } } } ```

### Pass Variables from MATLAB to .NET

The MATLAB `magic` function returns a 2-D matrix of type double. The engine converts the returned MATLAB 2-D double matrix to a .NET variable `dbls` declared as `double[,]`. You can then use `dbls` in your .NET program. For information about converting data from MATLAB to .NET, see Handle MATLAB Data in .NET Applications.

The C# code for this example is:

```using MathWorks.MATLAB.Engine; using MathWorks.MATLAB.Exceptions; using MathWorks.MATLAB.Types; using System; namespace MathWorks.MATLAB.Engine.ConsoleExamples { public class Program { public static void Main(string[] args) { Console.Write("Starting MATLAB... "); using (dynamic matlab = MATLABEngine.StartMATLAB()) { Console.WriteLine("done."); double[,] dbls = matlab.magic(3.0); matlab.disp(new RunOptions(nargout: 0), dbls); } // Call when you no longer need MATLAB Engine in your application. MATLABEngine.TerminateEngineClient(); } } }```

In this code, variable `dbls` is defined as a 2-D matrix of double. Alternative size definitions are:

```double[,] dbls = matlab.magic(3.0); // 3x3 double[,,] dbls = matlab.magic(3.0); // 3x3x1 Array dbls = matlab.magic(3.0); // 3x3```

This code shows size definitions for representing number `3.0`:

```double x = matlab.eval(" 3.0 "); // double scalar double[] y = matlab.eval(" 3.0 "); // double array, length 1 double[,,,] z = matlab.eval(" 3.0 "); // 1x1x1x1 Array q = matlab.eval(" 3.0 "); // 1x1```