1

I am trying to convert a matlab code to python due to lack of matlab. I will be grateful if you kindly tell me the python equivalents of the following functions which I could not find:

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

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

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

Thank you very much for your kind assistance.

3

2 Answers 2

3

I don't actually know matlab, but I can answer some of those (assuming you have numpy imported as 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
Sign up to request clarification or add additional context in comments.

2 Comments

mslice is not a built-in MATLAB function. ~ is for ignoring function return arguments
@Amro -- did I get the rest of the table approximately correct? (thanks by the way)
2

Converting from letter to number: ord("a") = 97

Converting from number to letter: chr(97) = 'a'

(You can subtract 96 to get the result you're looking for for lowercase, or 64 for uppercase.)

Parse a string to int: int("523") = 523

Comparing strings (Case sensitive): "Hello"=="Hello" = True

Case insensitive: "Hello".lower() == "hElLo".lower() = True

ones(): [1]*ARRAY_SIZE

Identity matrix: [[int(x==y) for x in range(5)] for y in range(5)]

To make 2-D arrays, you need to use numpy.

Edit:

Alternatively, you can make a 5x5 2-D array like so: [[1 for x in range(5)] for y in range(5)]

2 Comments

In this, trace could be implemented sum(a[i][i] for i in range(len(a)))
If the op is trying to replace matlab, I think assuming numpy is fair.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.