How to call a Python function that returns multiple values with Python Interface
13 ビュー (過去 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!