MATLAB Answers

Steven
1

How do I call a custom python function from matlab that uses an import statement?

Asked by Steven
on 13 Jul 2017
Latest activity Answered by Robert Snoeberger on 17 Jul 2017
I have a custom python script called testmat.py with two functions:
# testmat.py
import numpy
def createarray(n):
P = numpy.ones(2);
print(P)
return P
def createarray2(n):
P = 2;
print(P)
return P
def createarray3():
P = 3.14;
print(numpy.sin(P))
return P
I can call createarray2 from matlab by using these commands: testmat2 = py.importlib.import_module('testmat2');
>> testmat2.createarray2(2)
2
ans =
int64
2
However when I call createarray, matlab can't handle this request:
>> testmat2.createarray(2)
Error using numeric>ones (line 192)
Python Error: TypeError: 'float' object cannot be interpreted as an index
Error in testmat2>createarray (line 24)
P = numpy.ones(2);
How do I get matlab to use functions that use import statements.

  0 Comments

Sign in to comment.

Tags

1 Answer

Answer by Robert Snoeberger on 17 Jul 2017

Based on the error message, "TypeError: 'float' object cannot be interpreted as an index" you are passing a double when you should be passing an integer, such as in32. Try this:
>> testmat2.createarray(int32(2))
Note that the literal 2 is a double in MATLAB. When it is passed to Python, it is automatically converted to a Python float [1]. That is what the error message is complaining about.

  0 Comments

Sign in to comment.