addFunction
R2026bConfigure data transfer settings for Python method or function of PyTorchModel
Since R2026b
Description
addFunction(
adds or replaces the data-transfer configuration for the specified Python® method or function in the model,functionName,Name=Value)PyTorchModel object. The
name-value arguments describe how callFunction
converts MATLAB® numeric arrays to torch.Tensor objects, and vice versa,
when calling functionName using callFunction.
Given a PyTorchModel object, you can call any method of the
underlying PyTorch® model, or function taking the model as first argument, using
callFunction without declaring that method or function. Use
addFunction to change the data-transfer settings, or to declare
multiple inputs.
addFunction stores function configurations in the
PyTorchFunctions property of the PyTorchModel
object.
Examples
Input Arguments
Name-Value Arguments
Tips
The
NumInputsargument declares a fixed number of mandatory positional arguments for the function. At call time,callFunctionrequires exactlyNumInputspositional arguments, followed by any number of optional keyword arguments.If the underlying Python function accepts optional or variadic positional arguments, write a separate standalone Python function for each number of positional inputs you need, then add each one individually with
addFunction. For example, if you sometimes pass two inputs and sometimes three, definemy_func_2(model,x1,x2)andmy_func_3(model,x1,x2,x3), and add them withaddFunction(model,"myModule.my_func_2",NumInputs=2)andaddFunction(model,"myModule.my_func_3",NumInputs=3).Mandatory Python keyword arguments are handled by the optional keyword argument mechanism. If you omit a required keyword argument, Python issues an error at runtime.
If you get an "index out of range" error when calling the model, check whether any of the input tensors represent indices. PyTorch uses 0-based indexing, so you must subtract 1 from MATLAB 1-based indices before passing them to the model.
Version History
Introduced in R2026b
See Also
Functions
forward|callFunction|export|reload|importNetworkFromPyTorch|arrayToTorchTensor|torchTensorToArray