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?
You may follow NumPy for Matlab users page.
the[:]
is not equivalent to MATLAB the(:)
, you may use the.flatten()
&
in NumPy applies bitwise AND, use logical_and
instead. 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()))))