首页 > 解决方案 > 我需要帮助将 Matlab find() 语句转换为 Python

问题描述

在 Matlab 中计算以下索引:

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

所有数组的大小相同。我正在尝试将此索引转换为在 python 中使用并添加另一个参数。这是我到目前为止所拥有的:

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

这个想法是使用这个索引来查找数组中满足索引条件的所有值。当我尝试使用我制作的 Python 版本时,它返回错误:

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

我还没有让 a.all() 或 a.any() 工作。我需要使用这些吗?如果是这样,在这种情况下我该如何正确使用它们?

标签: pythonmatlabindexingvalueerror

解决方案


您可以关注NumPy for Matlab 用户页面。

  • NumPythe[:]不等同于 MATLAB the(:),您可以使用the.flatten()
  • &在 NumPy 中应用按位与,logical_and改为使用。
  • 而不是argwhere,使用nonzero.

您没有发布任何输入数据样本,因此发明了一些输入数据(用于测试)。

这是Python代码:

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()))))

推荐阅读