Home > Blockchain >  How can I pad a Swift array to make it bigger?
How can I pad a Swift array to make it bigger?

Time:10-12

I'm porting some Python code to Swift and am having trouble resizing one of my arrays.

I have a Swift 2D array of size 3640, but I want it to be of size 6960.

I am at a loss as for how to do this. What I'm looking for is something like NumPy's pad function, but for Swift.

Here's how I've accomplished this in Python:

# Let mfccs be a 2D NumPy array of shape [40,91] and size 3640

max_pad_len = 174

pad_width = max_pad_len - mfccs.shape[1]

# Resize mfccs from size 3640 to size 6960

mfccs = np.pad(mfccs, pad_width=((0, 0), (0, pad_width)), mode='constant')

# Now mfccs has a shape [40, 174] and size 6960

How can I convert this code to Swift? I'm sure it's very straightforward, but it is beyond my skills at the moment. I'd be extremely grateful for any help, as I have puzzled over this for a very long time.

CodePudding user response:

Given a 2D array and a max padding length:

let array2d = [[1, 2], [11, 12, 13], [21], [], [41, 42, 43, 44, 45]]
let maxPadLen = 4

you can pad it like this (note that it is done element-wise, since in Swift, a 2D array is an array of arrays and does not have a 2D shape like you could have in NumPy or Pandas):

let paddedArray2d = array2d.map {
    let padding = maxPadLen - $0.count
    if padding > 0 {
        return [Int](repeating: 0, count: padding)   $0
    } 
    return $0
} as [[Int]]

If you print out the initial array2d and the padded paddedArray2d, you would get:

Initial array:
[[1, 2], [11, 12, 13], [21], [], [41, 42, 43, 44, 45]]
Padded array:
[[0, 0, 1, 2], [0, 11, 12, 13], [0, 0, 0, 21], [0, 0, 0, 0], [41, 42, 43, 44, 45]]

Note how it is possible that there is an element with more items than maxPadLen, if you prefer to disallow it, you can do something when padding < 0 in the map function, for example, cut overflowing items.

  • Related