0
好吧,所以我有工作代码写在所有客观的c(是的,我知道objc技术上只是C.但我的意思是我有它写的消息和东西,我只有一个java的背景和不太了解普通老C),但它运行速度非常慢。所以我写了(我认为)是相同的代码,但是现在这组循环产生了不同的值(仅用于一些数字),并且在我的生活中,我无法弄清楚什么是不同的。我正在做的循环10次,并在matricies之间进行1次乘法和1次加法。我希望有更多的两种语言背景的人可以挑出我错误地转录的部分代码。我之前没有对任何数组进行任何修改(那些硬编码和未受影响的),所以A1,A2等在这两部分代码中都具有相同的值。用C转换目标C到C矩阵操作
当前代码:
for (int m = 0; m < 10; m++) {
//Do matrix multiplication between A1 and A2. Store in temporary B1
for(int i = 0; i < 13; i++)
for(int j = 0; j < 43; j++) {
double tempTotal = 0;
for(int k = 0; k < 43; k++){
tempTotal = tempTotal + A1[i][k] * A2[k][j];
}
B1[i][j] = tempTotal;
}
//Assign B1 data back into A1 after the multiplication is finished
for(int i = 0; i < 13; i++)
for(int j = 0; j<43; j++)
A1[i][j] = B1[i][j];
//Add C1 and A1. Store into C1.
for (int l = 0; l < 13; l++)
for (int n = 0; n < 43; n++)
C1[l][n] = C1[l][n] + A1[l][n];
}//end m for loop
这是旧的OBJ C代码:
for (int m = 0; m < 10; m++) {
//multiply A1 and A2. Store into A1
A1 = [LCA_Computation multiply:A1 withArray:A2]; //LCA_Computation is the name of the .m class file in which this all happens.
//Add C1 and A1. Store into C1
for (int i = 0; i < 13; i++)
for (int j = 0; j < 43; j++)
[[C1 objectAtIndex:i] replaceObjectAtIndex:j withObject:[NSNumber numberWithDouble: [[[C1 objectAtIndex: i] objectAtIndex: j] doubleValue] + [[[A1 objectAtIndex: i] objectAtIndex: j] doubleValue]]];
}//end m for loop
//multiply method
+ (NSMutableArray*)multiply:(NSMutableArray*)a1 withArray:(NSMutableArray*)a2
{
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;
}
//the String format is intentional. I convert them all to strings later. I just put it in the method here where as it is done later in the C code
[tempRow addObject:[NSString stringWithFormat:@"%f",tempTotal]];
}
[result addObject:tempRow];
}
return result;
}
你的加法和乘法代码看起来都是正确的。检查你的分配,确认你清除了数组,并通过valgrind运行它来检查细微的内存错误。 – dasblinkenlight
要求陌生人通过检查发现代码中的错误并不富有成效。您应该使用调试器(或打印语句)来确定代码行为分歧的地方,并使用一个小型简单数据集进行测试。 –
xcode是否有调试器,如果有,我该如何使用它?我已经使用了NSLog的各种地方并运行了大量的测试,但仍然没有成功。 – MrHappyAsthma