0

I need to translate a matlab code to python numpy code

I have 4 2-dimension arrays (A, B, C and D) and want to create a new one "res".

the code in matlab

index1 = find(A == 2 & B > C);
index2 = find(A == 2 & B >= D & B <= C);

res = uint8(zeros(100,100));
res(index1) = 5;
res(index2) = 4;

in Python/numpy I figured out I can create new arrays like this:

res = ((A == 2) & (B > C)) * 5
res = ((A == 2) & (B >= D) & (B <= C)) * 4

but how can I combine this 2 results in only one array? Like the matlab code does.

1 Answer 1

3

The translation (in this case) is almost one-for-one:

index1 = ((A == 2) & (B > C)) 
index2 = ((A == 2) & (B >= D) & (B <= C)) 
res = np.zeros((100, 100), dtype='uint8')
res[index1] = 5
res[index2] = 4

Alternatively, you could define res as

res = np.where(A == 2, np.where(B > C, 5, np.where(B >= D, 4, 0)), 0)

though I don't think that helps readability :)


PS. As Mr. E suggests, mask1 might be a better variable name than index1 since index (usually) suggests integer values while mask suggest booleans, which is what we have here.

Sign up to request clarification or add additional context in comments.

1 Comment

Can I be really pedantic and suggest not to use index1 for a boolean mask/array?

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.