1

The following index is computed in Matlab:

index = find(the(:) == lat & phi(:) == lon & ~isnan(dat(:)));

All the arrays are the same size. I am trying to convert this index for use in python and add another argument as well. This is what i have so far:

index = np.argwhere((the[:] == lat) & (phi[:] == lon) & (~np.isnan(dat[:])) & (start <= tim[:] <= stop))

The idea is to use this index to find all values in arrays that fulfill the conditions in the index. When i try to use the Python version i have made, it returns the error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I haven't gotten a.all() or a.any() to work. Do i need to use these? and if so how do i use them correctly in this case?

1
  • Please provide a minimal reproducible example, as well as the entire error message. Why all the [:], by the way? Also, I don't think you need to use argwhere() here. Commented Mar 6, 2020 at 2:05

1 Answer 1

1

You may follow NumPy for Matlab users page.

  • NumPy the[:] is not equivalent to MATLAB the(:), you may use the.flatten()
  • & in NumPy applies bitwise AND, use logical_and instead.
  • Instead of argwhere, use nonzero.

You didn't post any input data sample, so invented some input data (for testing).

Here is the Python code:

from numpy import array, logical_and, logical_not, nonzero, isnan, r_

# MATLAB code:
#the = [1:3; 4:6];
#lat = 3;
#phi = [5:7; 6:8];
#dat = [2, 3; 5, 4; 4, 6];
#lon = 7;
#index = find(the(:) == lat & phi(:) == lon & ~isnan(dat(:)));

# https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html
the = array([r_[1:4], r_[4:7]])
lat = 3
phi = array([r_[5:8], r_[6:9]])
dat = array([[2, 3], [5, 4], [4, 6]])
lon = 7

index = nonzero(logical_and(logical_and(the.flatten() == lat, phi.flatten() == lon), logical_not(isnan(dat.flatten()))))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.