Objective-C嵌套用于循环以创建矩阵重复项

时间:2019-03-22 13:55:25

标签: objective-c for-loop matrix

我正在用Objective-C(计算近交系数)开发iOS应用。我有一个for循环嵌套在for循环中以创建矩阵。在矩阵中寻找值时,我得到奇怪的输出,因此我添加了一些日志以查看是否可以查明发生了什么。为了获得矩阵的对角线值,我将计算中使用的值打印在一个特定的行/列值上。我的代码以某种方式用两个不同的值两次生成对角线值。我不明白这段代码是如何两次计算一个对角线值的:

for(x = 0; x < results.count; x++) {
    //Loop through all animals to create matrix columns
    NSMutableArray *rows = [[NSMutableArray alloc] init];
    i = 0;

for (i = 0; i < results.count; i++) {
    //Loop through all animals to create matrix rows
    int maleID = [[[results objectAtIndex:i] objectAtIndex:1] intValue];
    int femaleID = [[[results objectAtIndex:i] objectAtIndex:2] intValue];
    //NSString *animalID = [[results objectAtIndex:i] objectAtIndex:3];
    //NSLog(@"animal = %@ male = %d, female = %d",animalID,maleID,femaleID);

    if (i > x){
    //Above diagonal calculation
        //If male unknow tfemale male coefficient = 0
        if (maleID==-1) {
            maleCOE = 0;
        } else {
        maleCOE = [[rows objectAtIndex:maleID] floatValue];
        }

        //If female unknown tfemale female coefficient = 0
        if (femaleID==-1) {
            femaleCOE = 0;
        } else {
        femaleCOE = [[rows objectAtIndex:femaleID] floatValue];
        }

        //Calculate breeding pair COE
        float breedingCOE = (maleCOE + femaleCOE)/2;
        [rows addObject:[NSNumber numberWithFloat:breedingCOE]];
        if (x==7 && i==15) {
            NSLog(@"femaleID = %d, maleID = %d, femaleCOE = %f, maleCOE = %f, breedingCOE = %f",femaleID,maleID,femaleCOE,maleCOE,breedingCOE);
        }

}
    if (i < x) {
        //If below diagonal, use prior calculated breedingCOE from above diagonal
        float breedingCOE = [[[columns objectAtIndex:i] objectAtIndex:x]floatValue];
        [rows addObject:[NSNumber numberWithFloat:breedingCOE]];
    }

    if (i == x) {
        //Diagnal calculation
        if (maleID==-1 || femaleID==-1) {
            //If either parents unknow = 1
            [rows addObject:[NSNumber numberWithFloat:1]];
        } else {
            //Calculate individual COE
            float indCOE = 1 + ([[[columns objectAtIndex:femaleID] objectAtIndex:maleID]floatValue]/2);
            [rows addObject:[NSNumber numberWithFloat:indCOE]];
        }
        if (i==115 && x==115) {
            NSLog(@"femaleID = %d, maleID = %d, femaleCOE = %f, maleCOE = %f, indCOE =",femaleID,maleID,femaleCOE,maleCOE);
        }
    }
}
    //NSLog(@"row %d count = %lu",x,(unsigned long)rows.count);
    NSString *str = [rows componentsJoinedByString:@", "];
    //NSLog(@"%@",str);
    //Add row to column
    [columns addObject:rows];
}

0 个答案:

没有答案