How to call a Python function that returns multiple values with Python Interface
11 次查看(过去 30 天)
显示 更早的评论
MathWorks Support Team
2023-8-22
回答: MathWorks Support Team
2023-10-9
I have a Python function that returns multiple values. How can I call my Python function to return multiple values?
采纳的回答
MathWorks Support Team
2023-8-22
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"
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Call Python from MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!