Main Content

Create C# Code from Strongly Typed MATLAB Function

This example shows how to create C# (.cs) files from a strongly typed MATLAB® function and integrate it with sample C# application code.

Create Function in MATLAB

Create a strongly typed MATLAB function in a file named stronglyTypedFactorial.m with this code:

function fact = stronglyTypedFactorial(n)
arguments
    n (1,1) uint64 {mustBeReal, mustBeLessThan(n,22)}
end
fact = 1;
for i = 1:n
    fact = fact*i;
end
end

Test the function at the MATLAB command prompt.

stronglyTypedFactorial(5)
ans =
  uint64
   120

Generate C# Code

Generate the C# (.cs) file.

matlab.engine.typedinterface.generateCSharp("FactApp",Functions="stronglyTypedFactorial")
0 class(es) and 1 function(s) written to FactApp

The function creates the stronglyTypedFactorial.cs file in the folder FactApp. The code defines a C# class named MATLABFunctions containing functions to call the MATLAB stronglyTypedFactorial function with argument n of type UInt64.

The interface verifies that the input meets the mustBeReal argument. At run time, the MATLAB stronglyTypedFactorial function verifies that the input meets the mustBeLessThan(n,22) argument. For more information, see Data Type Mappings Between .NET and Strongly Typed MATLAB Code.

 stronglyTypedFactorial.cs

Integrate MATLAB-Generated C# Code with C# Application

Create a C# application file named Program.cs with this code.

 Program.cs

Compile and link the C# application. For more information, see Requirements to Build .NET Engine Programs.

Set the run-time library path.

  • Windows® Command Processor:

    set PATH=matlabroot\extern\bin\win64;%PATH%
  • Linux®:

    LD_LIBRARY_PATH=matlabroot/extern/bin/glnxa64:LD_LIBRARY_PATH
    export LD_LIBRARY_PATH
  • macOS:

    DYLD_LIBRARY_PATH=matlabroot/extern/bin/macos:matlabroot/sys/os/macos
    export DYLD_LIBRARY_PATH

    Replace macos with either maca64 for macOS with Apple silicon or maci64 for macOS with Intel®.

Run the application.

factApp.exe
Factorial of 5 is 120

See Also

| |

Related Topics