我有 2 个二维 NSMutableArrays,我正在尝试做一些基本的矩阵乘法。我在下面有我的通用公式代码,但它的性能非常慢(如预期的那样)。我做了很多谷歌搜索,但没有找到任何简单或易于理解的公式来更改代码以提高性能。谁能指出一个简单的公式/教程/示例的正确方向,说明如何在 Objective C 中使用矩阵乘法获得比 0(n^3) 更好的性能。
+ (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;
}