matlab调用python代码

科学计算或者写量化策略有时候需要用matlab去调用python的api,这里推荐一个简单的实现方法。
其实matlab比较新的版本中自带了一个适配组件可以直接调用python

系统函数

查看一下python的版本

>> pyversion

       version: '2.7'
    executable: 'D:\Programs\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\python.EXE'
       library: 'D:\Programs\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\python27.dll'
          home: 'D:\Programs\WinPython-64bit-2.7.10.3\python-2.7.10.amd64'
      isloaded: 1

调用python自带函数

简单的矩阵

>> ll = py.list([1, 2, 3, 4])

ll = 

  Python list with no properties.

    [1.0, 2.0, 3.0, 4.0]

多维度数组会被matlab阉割成一维的

>> array = py.list([[1, 2, 3], [4, 5, 6]])

array = 

  Python list with no properties.

    [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

matlab默认是浮点数,需要进行转换成整数

>> py.range(int32(7))

ans = 

  Python list with no properties.

    [0, 1, 2, 3, 4, 5, 6]

调用python第三方框架

numpy返回的矩阵直接对应matlab的矩阵

>> res = py.numpy.zeros([5, 5])

res = 

  Python ndarray with properties:

           T: [1x1 py.numpy.ndarray]
        base: [1x1 py.NoneType]
      ctypes: [1x1 py.numpy.core._internal._ctypes]
        data: [1x200 py.buffer]
       dtype: [1x1 py.numpy.dtype]
       flags: [1x1 py.numpy.flagsobj]
        flat: [1x1 py.numpy.flatiter]
        imag: [1x1 py.numpy.ndarray]
    itemsize: 8
      nbytes: 200
        ndim: 2
        real: [1x1 py.numpy.ndarray]
       shape: [1x2 py.tuple]
        size: 25
     strides: [1x2 py.tuple]

    [[ 0.  0.  0.  0.  0.]
     [ 0.  0.  0.  0.  0.]
     [ 0.  0.  0.  0.  0.]
     [ 0.  0.  0.  0.  0.]
     [ 0.  0.  0.  0.  0.]]

pandas返回的dataframe也是一样的

调用自定义python文件模块函数

假如有个自己写的test.py文件

def sum(a, b):
    return a + b

在同文件目录下建立test.m文件,并将matlab工作目录切到当前目录
可以在m文件里面写,或者在命令行里面写
方法1:

import py.test.*
res = sum(5, 7)

方法2:

>> res = py.test.sum(5, 7)

注意,
python文件被调用一次后会在matlab里面留下缓存函数,需要重启才可以清除。
python里面的对象可以赋值给matlab里面的变量,并且可以持有这个句柄调用对象函数。

发布了141 篇原创文章 · 获赞 424 · 访问量 116万+
展开阅读全文

python调用matlab的问题

12-13

# 在matlab运行函数时没有问题,但是用python调用该matlab函数时,出现报错如下。求问有遇到这种情况的吗? ``` import matlab.engine engine = matlab.engine.start_matlab() # Start MATLAB process engine.vl_compilenn label=engine.experi('/13/10.wav') print(label) ``` ``` Attempt to execute SCRIPT vl_nnconv as a function: /usr/local/MATLAB/R2017b/toolbox/MatConvNet/matconvnet-1.0-beta25/matlab/vl_nnconv.m Error in dagnn.Conv/forward (line 12) outputs{1} = vl_nnconv(... Error in dagnn.Layer/forwardAdvanced (line 85) outputs = obj.forward(inputs, {net.params(par).value}) ; Error in dagnn.DagNN/eval (line 91) obj.layers(l).block.forwardAdvanced(obj.layers(l)) ; Error in experi (line 68) dag.eval({'data', gpuArray(inp1)}) ; Traceback (most recent call last): File "/home/affcgroup/affc/Ser/affccompute/mcnCrossModalEmotions-master/emoVoxCeleb/p3.py", line 4, in <module> label=engine.experi('/home/affcgroup/mustudy/data/lianke/13/10.wav') File "/usr/local/lib/python2.7/dist-packages/matlab/engine/matlabengine.py", line 78, in __call__ _stderr, feval=True).result() File "/usr/local/lib/python2.7/dist-packages/matlab/engine/futureresult.py", line 68, in result return self.__future.result(timeout) File "/usr/local/lib/python2.7/dist-packages/matlab/engine/fevalfuture.py", line 82, in result self._result = pythonengine.getFEvalResult(self._future,self._nargout, None, out=self._out, err=self._err) matlab.engine.MatlabExecutionError: File /home/affcgroup/MatConvNet/matconvnet-1.0-beta25/matlab/+dagnn/Conv.m, line 12, in Conv.forward File /home/affcgroup/MatConvNet/matconvnet-1.0-beta25/matlab/+dagnn/Layer.m, line 85, in Layer.forwardAdvanced File /usr/local/MATLAB/R2017b/toolbox/MatConvNet/matconvnet-1.0-beta25/matlab/+dagnn/@DagNN/eval.m, line 91, in eval File /home/affcgroup/affc/Ser/affccompute/mcnCrossModalEmotions-master/emoVoxCeleb/experi.m, line 68, in experi Attempt to execute SCRIPT vl_nnconv as a function: /usr/local/MATLAB/R2017b/toolbox/MatConvNet/matconvnet-1.0-beta25/matlab/vl_nnconv.m ``` 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览