Skip to content

How to convert from Matrix to [Double] efficiently #5

Description

@mrvallejo

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
}

}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions