【问题标题】:Convert matlab statement to python [duplicate]将matlab语句转换为python [重复]
【发布时间】:2017-09-02 17:47:36
【问题描述】:

我应该在 python 中转换以下 matlab 语句:

lam = find(abs(b)>tol,1,'first')-1; 

提前致谢

【问题讨论】:

  • 如果您提供一些“实际的”b、tol 并展示 Matlab 的功能会很有用

标签: python matlab numpy scipy


【解决方案1】:

NumPy 无法获取第一个匹配的 not yet anyway

所以,我们需要用np.where 替换所有匹配的find,而numpy.abs 将替换abs。因此,它将是-

import numpy as np

lam = np.where(np.abs(a)>tol)[0][0]-1

因此,我们使用np.where(np.abs(a)>tol)[0] 获取所有匹配的索引,然后通过使用np.where(np.abs(a)>tol)[0][0] 对第一个元素进行索引来获取第一个索引,最后从中减去1,就像我们在MATLAB 上所做的那样。

示例运行 -

在 MATLAB 上:

>> b = [-4,6,-7,-2,8];
>> tol = 6;
>> find(abs(b)>tol,1,'first')-1
ans =
     2

在 NumPy 上:

In [23]: a = np.array([-4,6,-7,-2,8])

In [24]: tol = 6

In [25]: np.where(np.abs(a)>tol)[0][0]-1
Out[25]: 1 # 1 lesser than MATLAB vesion because of 0-based indexing

为了性能,我建议使用np.argmax 给我们第一个匹配的索引,而不是像这样使用np.where(np.abs(a)>tol)[0] 计算所有匹配索引 -

In [40]: np.argmax(np.abs(a)>tol)-1
Out[40]: 1

【讨论】:

  • argmax 如果没有第一个元素则失败
  • Anf 如果我想要“最后一个”而不是“第一个”?
  • @Linux np.where(np.abs(a)>tol)[0][-1].
  • 嗯好的。非常感谢您的支持。
猜你喜欢
  • 2020-06-18
  • 1970-01-01
  • 1970-01-01
  • 2012-12-25
  • 1970-01-01
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多