Search code examples
iosobjective-cmatrixaccelerate-framework

Matrix multiplication and inverse problems with accelerate framework


I am trying to multiply two matrices in Objective-C. I have imported the accelerate framework to my project in Xcode, everything compiles just fine. I did the matrix multiplication on my calculator and got correct values, however, when running the code, I do not. This is how I defined my matrices..

float matrixA [3][3] = {{-.045, -.141, -.079}, {-.012, -.079, .0578}, {.112, -.011, -.0830}};

float matrixB [3][1] = {{40}, {-61}, {98}};

I then used the mmul function in the accelerate framework..

vDSP_mmul(&matrixA[3][3], 1, &matrixB[3][1], 1, &results[3][1], 1, 3, 1, 3);

The array results was created by doing the following..

float results[3][1];

I just placed this in the viewDidLoad method of an empty project so I could NSLog the results. So when I multiply matrixA by matrixB I should get the following results.. (-1, 10, -3). However, the results in the NSLog show (-0.045, 0.000, 0.000). This is not correct and I don't understand why. My understanding was that this function would multiply two matrices together. But I am not sure what it is doing. I am probably inputing something incorrectly and was hoping someone could help me out.

Side Note: matrixA is really the inverse of another matrix. However, I can't find anything in the accelerate framework that will take the inverse. I did find a function called

sgetrf_

with LAPACK but don't really get it. If anyone has any help, advice, or some tutorial to follow I would appreciate it, been at this for three days now looking thing up on the internet!!


Solution

  • You are passing pointers to memory after the end of your matrices.

    Fixing that would look like this (untested code):

    vDSP_mmul(&matrixA[0][0], 1, &matrixB[0][0], 1, &results[0][0], 1, 3, 1, 3);
    

    Passing an array to a function in C will actually pass a pointer to the first element of the array, which in this case appears to be what you need to do. You were passing a pointer to a piece of memory directly after the final array element in your matrices, which means you'll get nonsense results, or a crash.