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

조회 수: 11 (최근 30일)
I have a Python function that returns multiple values. How can I call my Python function to return multiple values?
 

채택된 답변

MathWorks Support Team
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개)

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by