我正在寻找矢量(快速)代码,该代码可以执行 matlab find
函数的功能,无需循环。 find
返回给定函数的值和索引。 Swift 的过滤器、映射或归约不返回索引。
示例
X = [18 3 1 11; 8 10 11 3; 9 14 6 1; 4 3 15 21]
[row,col] = find(X>0 & X<10,3)
row =
2
3
4
col =
1
1
1
来自 matlab 文档
[row,col] = find(___) returns the row and column subscripts of each nonzero element in array X using any of the input arguments in previous syntaxes.
最佳答案
enumerate()
返回一个索引/元素对序列,可以
被过滤:
let vec = [18, 3, 1, 11, 8, 10, 11, 3, 9]
let result = filter(enumerate(vec), { (idx, elem) in elem > 2 && elem < 10 } )
println(result) // [(1, 3), (4, 8), (7, 3), (8, 9)]
或者,如果您只想要索引:
let indexes = filter(enumerate(vec), { (idx, elem) in elem > 2 && elem < 10 } ).map { $0.0 }
println(indexes) // [1, 4, 7, 8]
关于arrays - Matlab 向量查找的 Swift 版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30086454/