【问题标题】:matlab to python code conversionmatlab到python代码转换
【发布时间】:2012-07-25 08:48:17
【问题描述】:

由于缺少 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()

非常感谢您的热心帮助。

【问题讨论】:

标签: python matlab numpy scipy porting


【解决方案1】:

我实际上并不了解 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

【讨论】:

  • mslice 不是内置的 MATLAB 函数。 ~ 用于忽略函数返回参数
  • @Amro -- 我得到的表格的其余部分大致正确吗? (顺便谢谢)
【解决方案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)]

【讨论】:

  • 这里可以实现trace sum(a[i][i] for i in range(len(a)))
  • 如果 op 试图替换 matlab,我认为假设 numpy 是公平的。
猜你喜欢
  • 2014-01-23
  • 1970-01-01
  • 1970-01-01
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多