1

I have an array of 1000 elements, which elements fluctuate from 0 to 1.

I want to scan that array and zero all values below a certain threshold, let's say, 0.3.

I know I can do something like

let filteredArrayOnDict = myArray.filter { $0 > 0.3}

and I will get a new array with the elements above 0.3. But that is not what I want. I want to zero the elements below 0.3 and keep the resulting array with the same number of elements.

I can iterate over the array like

var newArray : [Double] = []
for item in myArray {
  if item > 0.3 {
    newArray.append(item)
  } else {
    newArray.append(0)
  }
}

but I wonder if there is some more elegant method using these magical commands like filter, map, flatmap, etc.

4

2 回答 2

6

The Accelerate framework has a dedicated function vDSP_vthresD for this purpose:

Vector threshold with zero fill; double precision.

Example:

import Accelerate

let array = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
var threshold = 0.3
var result = Array(repeating: 0.0, count: array.count)
vDSP_vthresD(array, 1, &threshold, &result, 1, vDSP_Length(array.count))
print(result) // [0.0, 0.0, 0.0, 0.3, 0.4, 0.5, 0.6]
于 2019-03-19T19:59:37.147 回答
4

You can try map for this

var resultArray = myArray.map({$0 > 0.3 ? $0 : 0})
于 2019-03-19T20:00:49.483 回答