0

I am looking for 2 things: a way to define a matrix in Swift and a way to diagonlize said matrix.

So far, I've found a way to make something that resembles a matrix using this:

var NumColumns = 2
var NumRows = 4
var array = Array<Array<Double>>()
for column in 0...NumColumns {
    array.append(Array(repeating:Double(), count:NumRows))
}

print(array)

But someone told me that this will not do because after I have the matrix I will need to use a diagonalization algorithm specifically on a matrix and not something similar to a matrix.

Any ideas?

loltospoon
  • 239
  • 1
  • 9
  • I'm no math guru so I don't know what "diagonalization" means. Questions about matrix typically are followed by "how can I do it really fast". For that, take a look into the [Accelerate Framework](https://developer.apple.com/reference/accelerate/vdsp) and see if something suits you. It written in C so won't be as elegant as a pure-Swift solution – Code Different Mar 06 '17 at 21:31

1 Answers1

1

The common way of defining matrices in different languages (including Swift) is row-major order. So, essentially your matrix is stored as contiguous array of rows. This will allow you to do most of linear algebra operations efficiently using Apple Accelerate framework. For your particular case, Apple has something already, however it won't be nicely documented neither will the API be "good-looking". Apple provides Swift bindings to LAPACK (Fortran based linear algebra library). To diagonalise your matrix you will need to find eigenvectors for it using dsyevd_ routine (http://www.netlib.org/lapack/explore-html/d2/d8a/group__double_s_yeigen_ga694ddc6e5527b6223748e3462013d867.html#ga694ddc6e5527b6223748e3462013d867). As an output of the function you will receive a matrix (represented in column-major order) of eigenvectors and a vector of eigenvalues (an array). If you transpose the matrix using another API function vDSP_mtransD (https://developer.apple.com/reference/accelerate/1450422-vdsp_mtransd) and create a diagonal matrix from eigenvalues, you will get matrices V and D for which the equation A = VDV' is satisfied. This is, as far as I understand, exactly what you're looking for.