Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Python 2D masked array similar to MATLAB's

I'm currently working in translating a MATLAB script to python. There is a step on the MATLAB code where I need to select entries from a matrix (2D array) based on a boolean matrix with the same dimensions. When I tried to write the equivalent code in Python I noticed that the elements in the resulting array were in a different order compared to the MATLAB. More precisely, MATLAB seems to select the elements in column-wise order, and Python in row-wise order. Is there a way to make Python output the array in MATLAB order?

Tiny example:

MATLAB:

a = [1, 2, 3; 4, 5, 6; 7, 8, 9];
b = [false, false, true; false, false, false; true, false, false];
a(b) % outputs [7;3] or [a(3,1); a(1,3)]

PYTHON:

import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
b= np.array([[False, False, True], [False, False, False], [True, False, False]]))
a[b] # outputs array([3,7]) or array([a[0,2], a[2,0])
like image 409
Feulo Avatar asked Apr 25 '26 16:04

Feulo


2 Answers

Expanding on the answer of Mikhail Genkin, one could use

a.T[b.T]

(a.T[b] gives the same result in this particular case since b is a symmetric matrix). Another option is

a.flatten('F')[b.flatten('F')]
like image 117
bb1 Avatar answered Apr 27 '26 04:04

bb1


How about transposing the array a in Python first?

 a.T[b]
like image 37
Mikhail Genkin Avatar answered Apr 27 '26 06:04

Mikhail Genkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!