Matrix icon indicating copy to clipboard operation
Matrix copied to clipboard

How to convert from Matrix to [Double] efficiently

Open mrvallejo opened this issue 6 years ago • 2 comments

Dear team,

I am learning a lot with your class about Accelerate!. I would like to ask you about how to reshape a Matrix to a Vector concatenating rows. Could you add a reshape function for this?

Example: /* Converts the matrix into a 2-dimensional array. */ public var array: [[Double]] { var a = [[Double]](repeating: [Double](repeating: 0, count: columns), count: rows) for r in 0..<rows { for c in 0..<columns { a[r][c] = self[r, c] } } return a }

Needed: /* Converts the matrix into a 1-dimensional array. */

I suggest you some additions that I have included by myself:

// MARK: - PERSONAL FUNCTIONS

extension Matrix{ // MARK: - Trigonometry /* Computes the sin of the Matrix */

public func sin() -> Matrix {
    var result = self
    grid.withUnsafeBufferPointer { src in
      result.grid.withUnsafeMutableBufferPointer { dst in
         var size = Int32(rows * columns)
         vvsin(dst.baseAddress!, src.baseAddress!, &size)
      }
    }
    return result
}

// MARK: - Thresholds

//Sets to zero the values <= to the threshold

public func thresholdZero(lhs: Double) -> Matrix {
    var results = self
    grid.withUnsafeBufferPointer { src in
      results.grid.withUnsafeMutableBufferPointer { dst in
        var scalar = lhs
        vDSP_vthresD(src.baseAddress!, 1, &scalar, dst.baseAddress!, 1, vDSP_Length(rows * columns))
      }
    }
    return results
}

//Sets to a +Scalar or the values <= to the threshold and -Scalar the others

public func thresholdValue(lhs: Double, sca: Double) -> Matrix {
    var results = self
    grid.withUnsafeBufferPointer { src in
      results.grid.withUnsafeMutableBufferPointer { dst in
        var scalar = lhs
        var value = sca
        vDSP_vthrscD(src.baseAddress!, 1, &scalar, &value, dst.baseAddress!, 1, vDSP_Length(rows * columns))
      }
    }
    return results
}

}

mrvallejo avatar Jan 04 '20 12:01 mrvallejo

Converting the matrix to a 1d array should be simple because it's already stored as a 1d array in memory. Just return the grid value. 😄

hollance avatar Jan 04 '20 14:01 hollance

Very appreciated for your fast answer! I am amateur developer. I have contacted you by LinkedIn in order to see if you offer your services to optimize a bit part of my code from Bucles to Accelerate.

mrvallejo avatar Jan 04 '20 19:01 mrvallejo