Saturday, August 13, 2011

Matrix manipulations on iPhone

iOS 4.0 has Accelerate Framework which allows easy matrix manipulations:
  1. Multiply a matrix by a vector: cblas_sgemv(CBLAS_ORDER order, CBLAS_TRANSPOSE transA, int M, int N, float alpha, float* A, int lda, float* X, int incX, float beta, float* Y, int incY ); this method actually does this: Y = alpha * A * X + beta * Y; Here X and Y are vectors and A is the matrix; Choosing various values of alpha and beta and by varying the initial value of Y it is possible to implement a range of equations. The basic idea is to pass the matrix or vector as one dimensional array and tell the method everything about their dimensions, e.g., how many rows, how many columns, etc. By changing "transA" one can get: Y = alpha* A' * X + beta * Y
  2. Multiply a matrix by a matrix: cblas_sgemm(CBLAS_ORDER order, CBLAS_TRANSPOSE transA, CBLAS_TRANSPOSE transB, int M, int N, int K, float alpha, float* A, int lda, float* B, int ldb, float beta, float* C, int ldc); this method gives: C = alpha * A * B + beta * C; Here A, B, and C are the matrices; Again the basic idea is to pass one dimensional arrays as matrices and tell the method whatever it needs to know, e.g., number of rows/columns etc. And using transA or transB one can get: C = alpha * A' * B + beta * C; C = alpha * A * B' + beta * C; and C = alpha * A' * B' + beta * C
  3. This link explains these two and many more linear algebra operations for iOS 4.0 pretty well. However, the parameter lda, ldb, or ldc should be the number of floats after which a new row (assuming order parameter is set for row-major) begins. For example, if the equation is: temp3 = H * preP; where H is a 3 x 9 matrix and preP is a 9 x 9 matrix, one can initialize temp3 with zeros and make this call: cblas_sgemm( 101, 111, 111, 3, 9, 9, 1, H, 9, preP, 9, 1, temp3, 9 ); Here, e.g., ldc = 9 because temp3 is a 3 x 9 matrix thus in row-major order the 2nd row is 9 floats away from the 1st row. On the other hand, if the equation is: temp2 = preP * H'; then initialize temp2 with zeros and make the call: cblas_sgemm( 101, 111, 112, 9, 3, 9, 1, preP, 9, H, 9, 1, temp2, 3 ); Here ldb = 9, because though here, H' is the "B" matrix, inside the memory there is only H, so the second row of H being 9 floats away (101 ensures row-major order) from its first row: ldb = 9.
  4. I missed MATLAB's back-slash, that remarkable, versatile operator. Accelerate Framework allows methods for solving triangular system of equations thus LU decomposition may need to be "manually" implemented.

No comments:

Post a Comment