[Python-MATLAB] 在Python中调用MATLAB的API

可以参考官方的说明文档:

http://cn.mathworks.com/help/matlab/matlab_external/get-started-with-matlab-engine-for-python.html

MATLAB Engine API的使用文档:

http://cn.mathworks.com/help/matlab/matlab-engine-for-python.html

原材料:

1、MATLAB 2015a  32位的

2、Python 2.7.13    32位的

安装:

1、运行cmd,切换到matlab的目录下:

C:\Program Files (x86)\MATLAB\MATLAB Production Server\R2015a\extern\engines\python

由于这个文件夹是在C盘的,安装时有可能会遇到写权限的问题。如果出现write permission,可以通过右击该文件夹,选择 属性->安全->编辑,给当前用户赋予完全控制的权限。

> python setup.py install

即可完成安装。

2、python中调用matlab的API示例:

#coding=utf-8
import matlab.engine

if __name__ == ‘__main__‘:
    eng = matlab.engine.start_matlab(‘MATLAB_R2015a‘)
    a = eng.sqrt(4.0)
    print type(a),a
    eng.quit()
    pass

在Python中创建MATLAB数组

1、创建1XN数组

import matlab.engine
A = matlab.int8([1,2,3,4,5])
print type(A),A.size,A

#输出:
<class ‘matlab.mlarray.int8‘> (1, 5) [[1,2,3,4,5]]

Attribute or Method


Purpose


size


Size of array returned as a tuple


reshape(size)


Reshape array as specified by sequence size

 2、创建多维数组

import matlab.engine
A = matlab.double([[1,2,3,4,5], [6,7,8,9,10]])
print(A)

3、在Python中索引MATLAB数组

这里的MATLAB数组索引跟在MATLAB的IDE里面不一样,MATLAB是从1开始,而在Python中是从0开始索引

import matlab.engine
A = matlab.int8([1,2,3,4,5])
print(A[0])

#输出:
[1,2,3,4,5]

由于A是1X5的矩阵,A[0]就是[1,2,3,4,5],如果要在A里面索引出4,则需要输入:

print A[0][3]

  

4、在Python中对MATLAB数组切片

这里语法跟Python中没多少差别,直接使用即可

import matlab.engine
A = matlab.int8([1,2,3,4,5])
print(A[0][1:4])

#输出:
[2,3,4]

切片赋值,也可以从一个MATLAB数组赋值到另一个MATLAB数组:

A = matlab.double([[1,2,3,4],[5,6,7,8]]);
A[0] = [10,20,30,40]
print(A)

#输出:
[[10.0,20.0,30.0,40.0],[5.0,6.0,7.0,8.0]]

A = matlab.int8([1,2,3,4,5,6,7,8]);
A[0][2:4] = [30,40]
A[0][6:8] = [70,80]
print(A)
#输出:
[[1,2,30,40,5,6,70,80]]

注意:

Note:   Slicing MATLAB arrays behaves differently from slicing a Python list. Slicing a MATLAB array returns a view instead of a shallow copy.
Given a MATLAB array and a Python list with the same values, assigning a slice results in different results as shown by the following code.
A = matlab.int32([[1,2],[3,4],[5,6]])
L = [[1,2],[3,4],[5,6]]
A[0] = A[0][::-1]
L[0] = L[0][::-1]
print(A)
[[2,2],[3,4],[5,6]]
print(L)
[[2, 1], [3, 4], [5, 6]]

数组reshape  

import matlab.engine
A = matlab.int8([1,2,3,4,5,6,7,8,9])
A.reshape((3,3))
print(A)
[[1,4,7],[2,5,8],[3,6,9]]

Python中MATLAB支持的数据类型:


matlab Class


Constructor Call in Python


matlab.double


matlab.double(initializer=None, size=None, is_complex=False)


matlab.single


matlab.single(initializer=None, size=None, is_complex=False)


matlab.int8


matlab.int8(initializer=None, size=None, is_complex=False)


matlab.int16


matlab.int16(initializer=None, size=None, is_complex=False)


matlab.int32


matlab.int32(initializer=None, size=None, is_complex=False)


matlab.int64[a]


matlab.int64(initializer=None, size=None, is_complex=False)


matlab.uint8


matlab.uint8(initializer=None, size=None, is_complex=False)


matlab.uint16


matlab.uint16(initializer=None, size=None, is_complex=False)


matlab.uint32


matlab.uint32(initializer=None, size=None, is_complex=False)


matlab.uint64[b]


matlab.uint64(initializer=None, size=None, is_complex=False)


matlab.logical


matlab.logical(initializer=None, size=None)[c]


matlab.object


No constructor. When a function returns a handle to a MATLAB object, the engine returns a matlab.object to Python.


[a] In Python 2.7 on Windows, matlab.int64 is converted to int32 in MATLAB. Also, MATLAB cannot return an int64 array to Python.

[b] In Python 2.7 on Windows, matlab.uint64 is converted to uint32 in MATLAB. Also, MATLAB cannot return a uint64 array to Python.

[c] Logicals cannot be made into an array of complex numbers.

奇异值分解示例:

#coding=utf-8
import matlab.engine
from numpy import *

if __name__ == ‘__main__‘:
    eng = matlab.engine.start_matlab(‘MATLAB_R2015a‘)
    A = matlab.double([[1,2],[5,6]])
    print type(A),A.size,A
    print eng.eig(A)
    eng.quit()
    pass

  

Examples and How To

Install MATLAB Engine API for Python

To start the MATLAB engine within a Python session, you first must install the engine API as a Python package.

Install MATLAB Engine API for Python in Nondefault Locations

By default, the installer builds the engine API for Python in the matlabroot\extern\engines\python folder. The installer installs the engine in the default Python folder.

Start and Stop MATLAB Engine for Python

Options for starting the MATLAB Engine for Python.

Connect Python to Running MATLAB Session

How to connect the MATLAB Engine for Python to a shared MATLAB session that is already running on your local machine.

Call MATLAB Functions from Python

How to return an output argument from a MATLAB function. How to read multiple outputs from a function. What to do when the MATLAB function does not return an output argument.

Call MATLAB Functions Asynchronously from Python

This example shows how to call the MATLAB sqrt function asynchronously from Python and retrieve the square root later.

Call User Script and Function from Python

This example shows how to call a MATLAB script to compute the area of a triangle from Python.

Redirect Standard Output and Error to Python

This example shows how to redirect standard output and standard error from a MATLAB function to Python StringIO objects.

Use MATLAB Engine Workspace in Python

This example shows how to add variables to the MATLAB engine workspace in Python.

Use MATLAB Handle Objects in Python

This example shows how to create an object from a MATLAB handle class and call its methods in Python.

Use MATLAB Arrays in Python

This example shows how to create a MATLAB array in Python and pass it as the input argument to the MATLAB sqrt function.

Sort and Plot MATLAB Data from Python

This example shows how to sort data about patients into lists of smokers and nonsmokers in Python and plot blood pressure readings for the patients with MATLAB.

Get Help for MATLAB Functions from Python

From Python, you can access supporting documentation for all MATLAB functions.

Concepts

Get Started with MATLAB Engine API for Python

The MATLAB Engine API for Python provides a Python package named matlab that enables you to call MATLAB functions from Python.

System Requirements for MATLAB Engine API for Python

What you need to write and build MATLAB engine applications.

Pass Data to MATLAB from Python

When you pass Python data as input arguments to MATLAB functions, the MATLAB Engine for Python converts the data into equivalent MATLAB data types.

Handle Data Returned from MATLAB to Python

When MATLAB functions return output arguments, the MATLAB Engine API for Python converts the data into equivalent Python data types.

MATLAB Arrays as Python Variables

The matlab Python package provides array classes to represent arrays of MATLAB numeric types as Python variables so that MATLAB arrays can be passed between Python and MATLAB.

Default Numeric Types in MATLAB and Python

MATLAB stores all numeric values as double-precision floating point numbers by default.

Troubleshooting

Limitations to MATLAB Engine API for Python

The engine cannot start or connect to MATLAB on a remote machine.

Troubleshoot MATLAB Errors in Python

When a MATLAB function raises an error, the MATLAB Engine for Python stops the function and catches the exception raised by MATLAB.

  

  

时间: 2024-10-08 07:00:17

[Python-MATLAB] 在Python中调用MATLAB的API的相关文章

Java中调用MatLab返回值

当在Java中使用MatLab函数时,由于语言语法的不同,Matlab返回多个数据时,想在Java中获取到并进行使用.查阅了网上资料,翻箱倒柜加上自己实战,得出方法如下: 如MatLab函数返回的是N个变量值,其中有单个的数值.一维数组.二维数组等. 在Java中,使用Object[] rs=cmatlab.matlabfun(n , ....);接受返回的参数.其中rs[k]代表返回列表中第k个返回的变量的值. 如果rs[k]是单个数值,比如Double型.则使用下面的方法转换为Java中的D

VC++中调用MATLAB中的数据

网上的帖子都是如何将VC++数据添加进入MATLAB中,而VC++调用MATLAB中的数据几乎没有,再次记录一点东西吧 配置好编程环境,本文环境为:VS2012+MATLAB2012b. 首先要了解的是Matlab Engine API函数 接下来贴代码和效果: void test2() { Engine *ep; if (!(ep = engOpen(NULL))) { cout<<"Can't start MATLAB engine"<<endl; //Me

python 中调用windows系统api操作剪贴版

# -*- coding: utf-8 -*- ''' Created on 2013-11-26 @author: Chengshaoling ''' import win32clipboard as w32 import win32con class OperateClipboard(object): def __init__(self): # print "OperateClipboard" pass def getText(self): w32.OpenClipboard()

c程序中调用matlab

c程序调用matlab 方法一: 在c程序中调用matlab引擎(相当于打开一个精简版matlab然后往里输入命令,即客户机/服务器模式, c程序为客户机,matlab作为本地服务器) 方法二:将m文件打包成dll文件,然后在c语言环境下调用 优缺点分析: 方法一,易于实现,可以实时监控程序的运行,但独立性差,速度慢,需要安装完整版matlab,且每次调用都会启动matlab.exe进程: 方法二,实现复杂,调试麻烦,但只需要安装mcr(matlab component runtime),耗费资

Haskell ghci中调用pandoc的API进行markdown转换

所用环境:Windows Server 2008 + ghc 7.6.3(Haskell Platform 2013.2.0.0自带的) + pandoc 1.12.4 操作步骤: 1. 安装Haskell Platform,下载地址:http://www.haskell.org/platform/. 2. 安装pandoc,安装命令:cabal install pandoc 3. 在命令行中运行ghci 4. 引用pandoc的相应模块,在Prelude命令提示符中运行: :module Te

C#中调用WIN32的API

最近在学习C#中的GDI部分,本来尝试编写一个字幕控件(其实还是用label比较合适),但是发现控件中用GDI将整个控件粉刷貌似不行(应该是我水平不行),所以就去捣鼓了下WIN32的DLL,发现用API还真是件幸福的事(仅在WIN32平台上说).回到C#,在C#中要在一个窗体(控件也是窗体),只要用    Graphics g=控件名.CreateGraphics();//这样就可以用g来在这个控件上画东西了.    但是如果我想不限范围,在整个屏幕上画,那么.NET就无能为力了.还好,我们有W

C#中调用Matlab人工神经网络算法实现手写数字识别

手写数字识别实现 设计技术参数:通过由数字构成的图像,自动实现几个不同数字的识别,设计识别方法,有较高的识别率 关键字:二值化  投影  矩阵  目标定位  Matlab 手写数字图像识别简介: 手写阿拉伯数字识别是图像内容识别中较为简单的一个应用领域,原因有被识别的模式数较少(只有0到9,10个阿拉伯数字).阿拉伯数字笔画少并且简单等.手写阿拉伯数字的识别采用的方法相对于人脸识别.汉字识别等应用领域来说可以采用更为灵活的方法,例如基于规则的方法.基于有限状态自动机的方法.基于统计的方法和基于神

在C#的Web项目中调用Matlab代码的方法

为了毕设的图形检索方向的研究,本人需要在信科的师兄师姐们已经完成的C#界面中,调用现在研究的算法的Matlab代码,以便看到实验的效果.前段时间已经拖延了1个多月,一方面因为实习越来越多事情,时间减少了很多:但更重要在于C#调用Matlab的方法真心麻烦,C#的Web项目中进行这个操作貌似会碰到更多细节上的问题.而且总是很不稳定,操作系统.Matlab或VS的版本.遗漏一些文件或步骤都会造成失败!这个问题本人已经搞了很长时间,直至前几天,在同学的帮助下,自己再弄一遍,总算成功了!下面我及时把这个

在代码中调用 mvc 4 api

mvc 4 api 的调用有很多种,最常见也最简单的一种是 用 ajax 的方式在前端界面中调用, 如果是在后台代码中调用 ,是要复杂一些,以下是 以 post 的方式调用 api 的封装好的方法: /// <summary> /// api 调用公共方法 /// </summary> /// <param name="url"> api url </param> /// <param name="param"&