Main Content

PyTorch Coexecution

Since R2025a

Before you can run simulations in MATLAB® and PyTorch®, you must first configure your computer for coexecution. You can then try some sample AI applications using the Example Workflows using Coexecution.

Set Up Environment for Coexecution

Make sure your computer is set up for configuration:

  • To call Python® modules in MATLAB, you must have a supported version of the reference implementation (CPython) installed on your system. For more information, see Configure Your System to Use Python.

  • Use the pyenv function to change the default version or execution mode of the Python interpreter. To check the interpreter configuration, view the PythonEnvironment object returned by the pyenv function.

    • By default, MATLAB selects the version of Python based on your system path. To use a specific Python version, specify the Version property when you call the pyenv function.

    • MATLAB selects and loads a Python interpreter when you type a Python expression from MATLAB using the py namespace, for example, py.list.

  • To debug Python code from MATLAB, see How can I debug Python code using MATLAB's Python Interface and Visual Studio Code in MATLAB Answers™.

Example Workflows using Coexecution

These examples demonstrate AI for of wireless applications using PyTorch coexecution.

Each example includes a requirements supporting file to identify the Python libraries that you need and their specific versions. You can use the requirements files with pip to install all the required libraries. For more information, see https://pip.pypa.io/en/stable/user_guide/.

  • To run each example, you can use the Python installed in a virtual environment or any other installation that includes the required Python libraries. To avoid potential conflicts between Python versions, follow guidance in Install Python in Virtual Environment to create a virtual environment.

  • To permit easy reconfiguring of the environment for initial simulation runs, the application examples have the ExecutionMode property set to 'OutOfProcess' for the pyenv function. Running Python functions out-of-process introduces overhead between MATLAB and Python that increases run time. For more information, see Out-of-Process Execution of Python Functionality.

  • Once you optimize the environment settings, switch the ExecutionMode property to InProcess to avoid overhead between the MATLAB and Python processes.

Note

After first loading pyenv with ExecutionMode set to 'InProcess', you must restart MATLAB to change the execution mode to 'OutOfProcess' and to change the Python version.

See Also

Topics