1

由于缺少 matlab,我正在尝试将 matlab 代码转换为 python。如果您能告诉我以下我找不到的函数的 python 等效项,我将不胜感激:

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

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

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

非常感谢您的友好帮助。

4

2 回答 2

3

我实际上并不了解 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
于 2012-07-26T17:44:54.247 回答
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)]

要制作二维数组,您需要使用numpy

编辑:

或者,您可以制作一个 5x5 二维数组,如下所示:[[1 for x in range(5)] for y in range(5)]

于 2012-07-26T17:41:13.613 回答