3

In want to implement the below listed Matlab commands in Python. I am able to figure out the Matlab equivalent commands in Python, but i am not getting the exact result. Can someone please help me to achieve so.

MATLAB CODE:

n0 = 3
n1 = 1
n2 = 5
n = [n1:n2]
>> 1 2 3 4 5
x = [(n - n0) == 0]
>> 0 0 1 0 0

PYTHON CODE:

import numpy 
n0 = 3
n1 = 1
n2 = 5
n = r_[n1:n2+1]
>> [1 2 3 4 5]
x = r_[(n-n0) == 0]
>> [False False True False False]

So x is my array with boolean data type " [array([False, False, True, False False], dtype=bool)]". How can i make my last command to return result in form of 0's or 1's such that result is exactly same as Matlab.

asked Aug 10, 2012 at 9:20

1 Answer 1

2

use a list comprehension to convert bool to int:

[int(val) for val in x]
answered Aug 10, 2012 at 9:26
Sign up to request clarification or add additional context in comments.

1 Comment

Thx, it can be used with array command such that the returned list is of ndarray data type. But is there a way that while i was executing the command, result will directly be in that type. I know there are some methods/attributes in numpy array by which data types can be controlled.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.