1

I am testing calling Python functions through MATLAB, but I am not getting what I expected. I figured I could call a Python function within MATLAB and have whatever that function returns, given to a MATLAB variable, as follows:

Python script (saved as test_for_mlab.py):

def out_func(arg_1):
    print 'This print statement is in Python'
    a = int(arg_1 * 10)
    return a

MATLAB part:

val = py.test_for_mlab.out_func(33);

I was expecting val to have a value of 330 (int). Instead, the message I get in MATLAB is val = Python NoneType with no properties. None.

How can I get my desired results?

Leo
  • 89
  • 7
  • 2
    It might help to refer to https://stackoverflow.com/questions/1707780/call-python-function-from-matlab – Hugh Bothwell Feb 01 '18 at 01:24
  • 1
    I get a `Python int with properties: ...` which has value 330, as expected. Using MATLAB R2017a and Python 3.6 from Anaconda. – hbaderts Feb 01 '18 at 07:04
  • @hbaderts Maybe it doesnt work for me because I am using Python 2.7. Strange that I am able to get print outputs into MATLAB but not return variables. – Leo Feb 01 '18 at 18:50

1 Answers1

0

My latest tests in Matlab 2022 suggest that the return of values only works with scripts but not with functions. A workaround is to write a simple wrapper script in Python, like so:

return_script.py:

 from return_value_test import main
 import sys
 a = main(sys.argv)

return_value_test.py:

 import sys
 
 def main(argv):
     print(argv)
     x = int(argv[1])
     a = x
     b = a + 1

     return b

 if __name__ == "__main__":
     main(sys.argv[1:])

How to call the script from Matlab with a command line parameter of 2, the return value of a should be 3 (original a + 1):

a = pyrunfile("return_script.py 2", "a")