What Does Find(X==1) in Matlab Exactly Return and What Is Equivalent to It in Python?

I'm trying to do what the following MATLAB code does in python but I can't quite understand the output of it. This is the MATLAB code

A = zeros((48,60));

A(3,5) = 1;
A(3,6) = 1;
A(48,60) = 1;
A(47,60) = 1;
A(24,30) = 1;
A(38,45) = 1;

f = find(A == 1);

The last line with f returns [195;243;1416;2150;2879;2880] which is a column of numbers. But I don't get how these numbers are obtained from find(). It seems like it isn't multiplying the row and column numbers. Why am I getting those numbers? Also, what should I do to get the same thing in python?

A= np.zeros(48, 60)
A[2, 4] = 1
A[2, 5] = 1
A[47, 59] = 1
A[46, 59] = 1
A[23, 29] = 1
A[37, 44] = 1

np.where(A ==1)

I've tried np.where(A== 1) but it only returns indices of the rows and columns.

1 Answer

The find command in matlab returns the linear indices of each element. More can be find here: .

The equivalent python code would then be np.argwhere which also returns the indices:

To get the exact same behavior as matlab, you have to transform the matrix into a vector:

A= np.zeros((48, 60))
A[2, 4] = 1
A[2, 5] = 1
A[47, 59] = 1
A[46, 59] = 1
A[23, 29] = 1
A[37, 44] = 1

np.argwhere(np.ravel(A)==1)
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest