matlab 调用 python

直接干是不行的:
在这里插入图片描述
来看看 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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值