2

I'm calling a python script from matlab. The python script needs 3 arrays as input arguments:

import sys
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect('equal')

X = np.array(float(sys.argv[1]), dtype =np. float32)
Y = np.array(float(sys.argv[2]), dtype =np. float32)
Z = np.array(float(sys.argv[3]), dtype =np. float32)

scat = ax.scatter(X, Y, Z)

I call the Python script from Matlab like this:

!"MYPATH\python.exe" test3.py dX dY dZ

In Matlab, dX, dY and dZ are all 1x500 array type. However, I get the following error:

ValueError: could not convert string to float: dX

It looks like the python script call doesn't evaluate the dX array and takes the argument as a string. How can I correct that?

1 Answer 1

1

There is no straightforward way to pass array arguments to command line programs. Basically, all the command line arguments will always be interpreted as strings, broken into words. You could pass the arrays in the command line as separate entries, but there is a limit to the length of the command line. I would recommend that you save the arrays in Matlab to a text file and then load them in the Python program:

In Matlab

filename = tempname;
data = [dX' dY' dZ'];
save(filename, 'data', '-ascii');
system(['"MYPATH\python.exe" test3.py "' filename '"']);

In Python:

dX, dY, dZ = np.loadtxt(sys.argv[1]).T
Sign up to request clarification or add additional context in comments.

4 Comments

Look like a promising solution, however I get the following error: ??? Error using ==> system Too many input arguments.
If I try system(['"MYPATH\python.exe"', 'test3.py'], filename);, I get the following error: Error using ==> system Unrecognized option: tempname.txt
I've changed the code to build the command correctly. Sorry about that, just another piece of Matlab inconsistency.
Works perfectly. Since MYPATH contains a space, i changed the system command to: system(['"MYPATH\python.exe" test3.py "' filename '"']);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.