简体   繁体   English

使用参数从Matlab调用Python脚本

[英]Calling Python script from Matlab with arguments

I'm calling a python script from matlab. 我正在从matlab调用python脚本。 The python script needs 3 arrays as input arguments: python脚本需要3个数组作为输入参数:

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: 我这样从Matlab调用Python脚本:

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

In Matlab, dX , dY and dZ are all 1x500 array type. 在Matlab中, dXdYdZ均为1x500数组类型。 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. 看起来python脚本调用不会评估dX数组,而是将参数作为字符串。 How can I correct that? 我该如何纠正?

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: 我建议您save Matlab中的数组save到文本文件,然后将其加载到Python程序中:

In Matlab 在Matlab中

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

In Python: 在Python中:

dX, dY, dZ = np.loadtxt(sys.argv[1]).T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM