【问题标题】:I need help converting Matlab find() statement to Python我需要帮助将 Matlab find() 语句转换为 Python
【发布时间】:2020-06-18 13:47:39
【问题描述】:

在 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() 工作。我需要使用这些吗?如果是这样,在这种情况下我该如何正确使用它们?

【问题讨论】:

  • 请提供minimal reproducible example,以及完整的错误消息。顺便说一句,为什么所有[:]?另外,我认为您不需要在这里使用argwhere()

标签: python matlab indexing valueerror


【解决方案1】:

您可以关注NumPy for Matlab users 页面。

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

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

这里是 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()))))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    相关资源
    最近更新 更多