2012-05-23 59 views
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; 
} 
+1

你的加法和乘法代碼看起來都是正確的。檢查你的分配,確認你清除了數組,並通過valgrind運行它來檢查細微的內存錯誤。 – dasblinkenlight

+1

要求陌生人通過檢查發現代碼中的錯誤並不富有成效。您應該使用調試器(或打印語句)來確定代碼行爲分歧的地方,並使用一個小型簡單數據集進行測試。 –

+0

xcode是否有調試器,如果有,我該如何使用它?我已經使用了NSLog的各種地方並運行了大量的測試,但仍然沒有成功。 – MrHappyAsthma

回答

0

這個問題曾與造成的0在某些計算中使用之前內存管理問題做。