【问题标题】:How could I translate the command find of MATLAB to Python? [duplicate]如何将 MATLAB 的命令 find 转换为 Python? [复制]
【发布时间】:2021-03-04 21:23:47
【问题描述】:

我在 Matlab 的一个程序中有这个迭代,想把它翻译成 Python,但我的问题在于 'n' 和 'direction' 的参数。

for i=1:size(labels)
    idx_V=[idx_V;find(y(idxUnls(trial,:))==labels(i),l/length(labels),'first')]
end

【问题讨论】:

  • 这些参数有什么问题?
  • 我找不到复制它们的方法。我发现一个类似的命令是numpy.argwhere(),但它没有考虑这些参数。
  • 这些参数是什么意思?这段代码应该做什么?

标签: python python-3.x matlab


【解决方案1】:

在 Python 中,MATLAB 的 find 函数没有一对一的交换。受到another answer here的启发,我提出以下解决方案:

% MATLAB
inds = find(myarray == condition, n, 'first')
# Python
import numpy as np
inds = [ind for (ind, val) in np.ndenumerate(myarray == condition) if val]
inds = inds[0:n]

我敢肯定,与ndenumerate 相比,考虑到find 哪个维度首先运行,我确信可能需要考虑一些技巧。 Python 表达式也可以构造为生成器。

如果您想要类似的实现,则必须自己用 Python 编写。

【讨论】:

  • 另外,如果试图实现最大的灵活性,np.nditer 可能是最后的结果。
猜你喜欢
  • 2017-12-12
  • 2015-01-18
  • 2015-04-26
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-18
  • 1970-01-01
相关资源
最近更新 更多