標籤:

在matlab2015a中如何調用python?

matlab2015a似乎已經已經支持調用python了,但是好像不怎麼清楚如何調用python,可以直接調用python腳本文件么,而且可能還需要import一些其他的庫,比如sklearn


其實Matlab的幫助是寫得很詳細了。我主要做科學計算的,說說用於數值計算上的幾點。

Python其實比Matlab在字元串處理上強很多,數值計算倒不一定強的。

安裝好2015a和python(我是直接用的python的distribution Anaconda),不要做其它設置,就可以直接在matlab里調用python。

查看一下python的版本

&>&> pyversion

version: "2.7"
executable: "D:program filesanacondapython.EXE"
library: "D:program filesanacondapython27.dll"
home: "D:program filesanaconda"
isloaded: 1

首先是簡單的產生矩陣:

&>&> py.list([2,3,5,10])

ans =

Python list with no properties.

[2.0, 3.0, 5.0, 10.0]

現在這個結果是list屬性。這裡這個list功能被「閹割」了,對多維數組作用時是這樣的,會將多維數組轉化成一維的。

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

ans =

Python list with no properties.

[1.0, 2.0, 3.0, 4.0]

索引方法和原Python語言有區別

&>&> ans{4}

ans =

10

由於matlab中默認使用浮點數,有的要轉化成整數後運行

&>&> py.range(int64(10))

ans =

Python list with no properties.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

python有強大的numpy包。可以調用numpy包來產生矩陣,

&>&> py.numpy.zeros([3,3])

ans =

Python ndarray with properties:

T: [1x1 py.numpy.ndarray]
base: [1x1 py.NoneType]
ctypes: [1x1 py.numpy.core._internal._ctypes]
data: [1x72 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: 72
ndim: 2
real: [1x1 py.numpy.ndarray]
shape: [1x2 py.tuple]
size: 9
strides: [1x2 py.tuple]

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

現在這個結果是ndarray屬性,使用py.list變成list屬性

&>&> py.list(ans)

ans =

Python list with no properties.

[array([ 0., 0., 0.]), array([ 0., 0., 0.]), array([ 0., 0., 0.])]

再用py.list作用一次得到元素。

也可以直接使用.tolist變成list屬性,這樣就可以進行索引了

&>&> t1=py.numpy.zeros([2,2]);
&>&> t1.tolist

ans =

Python list with no properties.

[[0.0, 0.0], [0.0, 0.0]]
&>&> ans{1}{1}

ans =

0

py.list可以作用於Matab的向量,得到python的list,但不能作用於多維數組。然後,把python的list轉化為matlab能用的向量時,可以用cellfun

&>&> x1=1:1:5;py.list(x1)

ans =

Python list with no properties.

[1.0, 2.0, 3.0, 4.0, 5.0]

p1=py.list([1,2,3,4]);p2=cellfun(@double,cell(p1))

p2 =

1 2 3 4

matlab裡面的高維數組不能直接由py.list不能直接轉換成python的list,一個曲折的方法的高維矩陣matlab里reshape成向量,append到空的ndarray里再reshape回來,有些麻煩。或是如下所示,利用循環來賦值,同樣的方法也可以利用下面的循環來將matlab里的高維數組轉換成python的list。有找到好方法的請告知一下。

t1=py.numpy.random.random([2,2,2]);
t2=t1.tolist;
&>&> for i1=1:2
for j1=1:2
for k1=1:2
t2{i1}{j1}{k1}=1;
end
end
end
&>&> t2

t2 =

Python list with no properties.

[[[1.0, 1.0], [1.0, 1.0]], [[1.0, 1.0], [1.0, 1.0]]]

再說一下一下畫圖包matplotlib的調用。這裡 import這個庫里,可以到pyplot.*,但是因為這個庫很多函數和matlab同名,後面很多matlab的命令會被這個庫的命令覆蓋。

&>&> t1=py.numpy.linspace(1,10,10);
import py.matplotlib.*
pyplot.figure
pyplot.plot(t1)
pyplot.savefig("test1.png")
%pyplot.show()
figure(1)
imshow("test1.png")

ans =

Python Figure with properties:

axes: [1x0 py.list]
dpi: 80
suppressComposite: [1x1 py.NoneType]
callbacks: [1x1 py.matplotlib.cbook.CallbackRegistry]
clipbox: [1x1 py.NoneType]
texts: [1x0 py.list]
eventson: 0
patch: [1x1 py.matplotlib.patches.Rectangle]
number: 15
figurePatch: [1x1 py.matplotlib.patches.Rectangle]
images: [1x0 py.list]
bbox_inches: [1x1 py.matplotlib.transforms.Bbox]
transFigure: [1x1 py.matplotlib.transforms.BboxTransformTo]
patches: [1x0 py.list]
figure: [1x1 py.NoneType]
frameon: 1
lines: [1x0 py.list]
bbox: [1x1 py.matplotlib.transforms.TransformedBbox]
artists: [1x0 py.list]
legends: [1x0 py.list]
subplotpars: [1x1 py.matplotlib.figure.SubplotParams]
dpi_scale_trans: [1x1 py.matplotlib.transforms.Affine2D]
canvas: [1x1 py.matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg]

Figure(640x480)

ans =

Python list with no properties.

[&]

這是一種調用matplotlib繪圖的方法,也支持import 其它python的包,但調用格式沒有在python里自由。

這裡使用pyplot的show命令里雖然可以顯示圖像,但一旦激活它的圖像窗口,matlab就崩潰了,不知道是什麼原因,期待解決(最新測試:在安裝了2014b版本的電腦上show()顯示圖片,測試起來沒有這個問題,使用其它版本也沒有這個問題,不知道是2015a的版本問題還是安裝有問題?)。所在我這裡採用的方法是保存圖像後用matlab的imshow命令來顯示出來,顯然這不是一個好方法。應該是使用上面的pyplot.show()來顯示圖像更好。

關於matlab調用自定義函數的問題,其實和上面的調用庫的方法類似,庫本身就是一些定義的函數的集合。

如果有一個test1.py文件,是一個"script"如下

a=2
b=3
c=a+b
print(c)

這時,可以這樣執行得到c的值

py.test1.c

ans =

5

如果有一個test.py文件,裡面含有"function"如下

def c1(a1,b1):
c=a1+b1
return c

這時可以這樣調用這個函數

&>&> py.test.c1(5,5)

ans =

10

也可以先import這個「包」,再使用函數

&>&> import py.test.*
&>&> c1(10,10)

ans =

20

這裡我試驗了一下,這個test.py文件名改為test1.py文件就不能執行,不知道是什麼原因。

後面隨著使用經驗的增加,可能會隨時增補一些內容。


最近大作業想用深度增強學習做ACC,車的模型是simulink里的模型,想用python寫演算法,但是直接在maltab里調用python又有一些麻煩,所以就寫了讓matlab和python用socket通信,同時用一個m文件控制simulink模型的運行。

大概功能是,python傳給matlab一個參數,把這個參數賦值到simulink的一個模塊上,然後模型運行一個步長,返回一些結果再傳遞給python。

通信速度挺快的,感覺這個方法也算比較方便。

通信的代碼和模型詳見sherrysherryli/simulink-python-communication

參考文章:matlab與python SOCKET通信--UDP方法與TCP方法


頂 @ge yin 的答案,說的很詳細了。

補充一點:

如果不幸如題主,在窗口輸入pyversion後,返回的

version:

executable:

等變數均為空後,可嘗試輸入 pyversion python.exe的執行路徑 即可。

感謝MATLAB的幫助文檔,大部分信息參見Call Python Libraries條目。

人生苦短


Command Window下輸入help py,有幫助。


所謂 "有幫助" 的回復就別賣弄了,天下人都知道


推薦閱讀:

最好的 Python 網站開發方面的學習教程有哪些?
python把一個unicode字元串寫入文件為什麼會報錯?
正則表達式如何匹配網頁裡面的漢字?
已經有了各省的數據,如何將信息以可視化的方式顯示在地圖上?順便問一下python有相關的第三方包沒?

TAG:Python | MATLAB |