matlab把所有参数输出到一个文件里,然后用system命令调python脚本。python脚本读文件做计算结果再写文件。最后matlab再读文件得到结果。假设python脚本的用法是:
python xxx.py in.txt out.txt
则matlab调用的命令:
[status, cmdout] =
system
(
'python xxx.py in.txt out.txt'
)
Matlab的system函数用来向操作系统发送一条指令,并得到控制台的输出,可以直接将控制台的输出在Command Window打印出来,或者保存在变量中。 与system类似的还有dos函数和unix函数,我觉得它们都是对system函数的一种包装,而Matlab的system函数也许是对C的库函数system的包装。
先编写一个调用Python脚本的matlab程序即python.m
function [result status] = python(varargin)
% call python
%命令字符串
cmdString='python';
for i = 1:nargin
thisArg = varargin{i};
if isempty(thisArg) | ~ischar(thisArg)
error(['All input arguments must be valid strings.']);
elseif exist(thisArg)==2
%这是一个在Matlab路径中的可用的文件
if isempty(dir(thisArg))
%得到完整路径
thisArg = which(thisArg);
end
elseif i==1
% 第一个参数是Python文件 - 必须是一个可用的文件
error(['Unable to find Python file: ', thisArg]);
end
% 如果thisArg中有空格,就用双引号把它括起来
if any(thisArg == ' ')
thisArg = ['"', thisArg, '"'];
end
% 将thisArg加在cmdString后面
cmdString = [cmdString, ' ', thisArg]
end
%发送命令
[status,result]=system(cmdString);
end
就可以用这个函数调用python脚本了。 下面就来个调用python脚本matlab_readlines.py(保存在matlab当前目录)的例子
import sys
def readLines(fname):
try:
f=open(fname,'r')
li=f.read().splitlines()
cell='{'+repr(li)[1:-1]+'}'
f.close()
print cell
except IOError:
print "Can't open file "+fname
if '__main__'==__name__:
if len(sys.argv)<2:
print 'No file specified.'
sys.exit()
else:
readLines(sys.argv[1])
这个脚本用来读取一个文本文件,并生成Matlab风格的cell数组的定义字符串,每个单元为文本的一行。 放了一个测试用的文本文件test.txt在Matlab的Current Directory中,内容如下:
This is test.txt
It can help you test python.m
and matlab_readlines.py
测试:
在Matlab的Command Window中输入:
>> str=python('matlab_readlines.py','test.txt');
>> eval(['c=' str])
c =
'This is test.txt' [1x29 char] [1x23 char]
>> celldisp(c)
c{1} = This is test.txt
c{2} = It can help you test python.m
c{3} = and matlab_readlines.py