How to call a Python function that returns multiple values with Python Interface

13 Ansichten (letzte 30 Tage)
I have a Python function that returns multiple values. How can I call my Python function to return multiple values?
 

Akzeptierte Antwort

MathWorks Support Team
MathWorks Support Team am 22 Aug. 2023
When a Python function returns multiple values, these values will be returned to MATLAB as a single Python tuple object. To retrieve individual values, you will need to unwrap the tuple. This can be illustrated with the Python code below.
# WordCount.py
def CountWords(text):
# remove spaces
text = text.strip()
# remove punctuation
text = text.translate({ord(i): None for i in ',.;\/!?-_`|><'})
# convert to lowercase
text = text.lower()
word = text.split()
return len(word), word
The "CountWords" function takes a string as an input argument, removes punctuation, converts to lowercase, and returns the number of words and a list of the words. The following steps show how to call the function and access the individual return values.
Create a string
>> s="The cow jumped over the moon.";
Call the Python function with a single return variable "pyvals".
>> pyvals = py.WordCount.CountWords(s)
pyvals =
Python tuple with values:
(6, ['the', 'cow', 'jumped', 'over', 'the', 'moon'])
Use string, double or cell function to convert to a MATLAB array.
The word count (6) and the list of words are contained in the tuple. Convert the tuple to a MATLAB cell array
>> mlvals = cell(pyvals)
mlvals =
1×2 cell array
{1×1 py.int} {1×6 py.list}
Now extract the individual return values. Convert the word count to a MATLAB int32  value.
>> numWords = int32(mlvals{1})
numWords =
int32
6
Convert the list of words to a MATLAB string array.
>> Words = string(mlvals{2})
Words =
1×6 string array
"the" "cow" "jumped" "over" "the" "moon"

Weitere Antworten (0)

Kategorien

Mehr zu Call Python from MATLAB finden Sie in Help Center und File Exchange

Tags

Noch keine Tags eingegeben.

Produkte


Version

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by