2012-07-26 190 views
1

我想轉換一個matlab代碼爲python由於缺乏matlab。我會很感激,如果不能請你告訴我的以下功能,我找不到蟒蛇當量:matlab到python代碼轉換

letter2number_map('A') = 1; 
number2letter_map(1) = 'A'; 
str2num() 

strcmp() 
trace() 
eye() 
getenv('STRING') 

[MI_true, ~, ~] = function() What does ~ mean? 
mslice 
ones() 

非常感謝你的善意幫助。

+1

如果你缺乏matlab爲什麼不給octave或SciLab一個機會? – 2012-07-26 18:06:37

+1

見http://www.scipy.org/NumPy_for_Matlab_Users/ – tacaswell 2012-07-26 18:39:49

+0

相關:http://stackoverflow.com/questions/9845292/converting-matlab-to-python?rq=1 – 2013-08-26 04:38:15

回答

2

我真的不知道MATLAB,但我可以回答一些人的(假設你有numpy的進口作爲np):

letter2number_map('A') = 1; -> equivalent to a dictionary: {'A':1}  
number2letter_map(1) = 'A'; -> equivalent to a dictionary: {1:'A'} 

str2num() -> maybe float(), although a look at the docs makes 
      it look more like eval -- Yuck. 
      (ast.literal_eval might be closest) 
strcmp() -> I assume a simple string comparison works here. 
      e.g. strcmp(a,b) -> a == b 
trace() -> np.trace() #sum of the diagonal 
eye()  -> np.eye()  #identity matrix (all zeros, but 1's on diagonal) 
getenv('STRING') -> os.environ['STRING'] (with os imported of course) 
[MI_true, ~, ~] = function() -> Probably: MI_true,_,_ = function() 
           although the underscores could be any 
           variable name you wanted. 
           (Thanks Amro for providing this one) 
mslice -> ??? (can't even find documentation for that one) 
ones() -> np.ones()  #matrix/array of all 1's 
+0

'mslice'不是內置的MATLAB函數。 '〜'用於忽略函數返回參數 – Amro 2012-07-26 17:58:12

+0

@Amro - 我是否已經使表格的其餘部分大致正確? (順便說一下) – mgilson 2012-07-26 18:00:24

+0

據我所知可以是+1 – Amro 2012-07-26 18:02:43

2

轉換從信號碼:ord("a") = 97

轉換從數信:chr(97) = 'a'

(你可以減去96來獲得你正在尋找小寫,或64大寫的結果)

解析字符串爲int:int("523") = 523

比較字符串(區分大小寫):"Hello"=="Hello" = True

不區分大小寫:"Hello".lower() == "hElLo".lower() = True

ones()[1]*ARRAY_SIZE

單位矩陣:[[int(x==y) for x in range(5)] for y in range(5)]

爲了使2-d數組,你需要使用numpy

編輯:

或者,你可以做一個5x5的2-d陣列像這樣:[[1 for x in range(5)] for y in range(5)]

+0

在這裏,可以實施「trace」 'sum(a [i] [i]我在範圍內(len(a)))' – mgilson 2012-07-26 17:52:22

+0

如果op正在嘗試替換matlab,我認爲假設numpy是公平的。 – tacaswell 2012-07-26 18:38:55