直接干是不行的:
来看看 python 快速入门:
朕的 matlab2016b 居然只支持到 python 3.5。
那就装个 3.5 吧 。。。
朕怎么可能去装 3.5 呢, 这辈子都不可能装 3.5 的。
然后不记得在哪找到了下面这种方法,可能是官方(大佬)教程吧:
自定义函数 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
cmdString
%发送命令
[status,result]=system(cmdString);
end
被调用的 python 文件
注意输出时的格式:
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])
被处理的文件
This is test.txt
It can help you test python.m
and matlab_readlines.py
运行效果
>> str = python('matlab_readlines.py','test.txt')
cmdString =
python matlab_readlines.py test.txt
str =
{'This is test.txt ', 'It can help you test python.m ', 'and matlab_readlines.py'}
bingo!