Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - Matrix Multiplication Slow Performance

I have 2 2-D NSMutableArrays and I am trying to do some basic matrix multiplication. I have my generic formula code below, but its performance is exceptionally slow (as expected). I have done lots of googling and have not found any easy nor easy to understand formulas to change up the code for performance enhancement. Can anyone point me in the right direction of a straightforward formula/tutorial/example of how to get better performance than 0(n^3) with matrix multiplication in Objective C.

+ (NSMutableArray*)multiply:(NSMutableArray*)a1 withArray:(NSMutableArray*)a2
{
    if([[a1 objectAtIndex: 0] count] != [a2 count])
    {
        NSLog(@"Multiplicaton error!");
        return NULL;
    }

    int a1_rowNum = [a1 count];
    int a2_rowNum = [a2 count];
    int a2_colNum = [[a2 objectAtIndex:0] count];
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:a1_rowNum];
    for (int i = 0; i < a1_rowNum; i++) {
        NSMutableArray *tempRow = [NSMutableArray arrayWithCapacity:a2_colNum];
        for (int j = 0; j < a2_colNum; j++) {
            double tempTotal = 0;
            for (int k = 0; k < a2_rowNum; k++) {
                double temp1 = [[[a1 objectAtIndex:i] objectAtIndex:k] doubleValue];
                double temp2 = [[[a2 objectAtIndex:k] objectAtIndex:j] doubleValue];
                tempTotal += temp1 * temp2;
            }
             //Stored as a string because I upload it to an online database for storage.
            [tempRow addObject:[NSString stringWithFormat:@"%f",tempTotal]];
        }
        [result addObject:tempRow];
    }
    return result;
}
like image 836
MrHappyAsthma Avatar asked Mar 18 '26 07:03

MrHappyAsthma


1 Answers

It will be much faster if you Write it in C.


double[] will be ridiculously fast compared to an NSArray of NSNumbers for this task. you'll have good cache coherency, minimal instructions, no need to go through the runtime or allocate in order to write or read an element. no need to perform reference count cycling on each element…

like image 188
justin Avatar answered Mar 19 '26 20:03

justin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!