callFunction
R2026bCall method of underlying Python PyTorch model instance or function taking model as its first argument
Since R2026b
Syntax
Description
[
passes Y1,...,YN] = callFunction(model,functionName,X1,...,XM)X1,...,XM to Python®, converting any numeric MATLAB® arrays to torch.Tensor objects, and calls
functionName on the model and Python inputs.
[___] = callFunction(___,
also passes Python keyword arguments to the function call.pyarg1=val1,...,pyargK=valK)
[___] = callFunction(___,ReturnAsPython=[
specifies which outputs to return as Python types (tf1,...,tfN])py.* objects) rather than converting them to
MATLAB arrays. If you specify ReturnAsPython, it must appear after
all Python keyword arguments.
Examples
Input Arguments
Output Arguments
Tips
callFunctionsupports a fixed number of mandatory positional arguments followed by optional keyword arguments. The number of mandatory positional arguments is set by theNumInputsargument ofaddFunction(default 1). At call time, you must pass exactlyNumInputspositional arguments afterfunctionName, followed by any number of 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 use
addFunctionandcallFunctionto call them individually. For example, definemy_func_2(model,x1,x2)that takes two inputs, add it withaddFunction(model,"myModule.my_func_2",NumInputs=2), and call it withcallFunction(model,"myModule.my_func_2",X1,X2).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.
Algorithms
Version History
Introduced in R2026b
See Also
Functions
forward|addFunction|export|reload|importNetworkFromPyTorch|arrayToTorchTensor|torchTensorToArray
Objects
PyTorchModel|dlarray|(Parallel Computing Toolbox)gpuArray