Im interested in doing some matrix calculations in objective-C (for an iPhone app).
A score should be calculated for every element in the matrix, but I can’t even get my initialization of the matrix to work.
The algorithm i’m trying to implement is called the Needleman-Wunsch algorithm, is used to align nucleotide sequences.
Currently, I am trying to initialize a 2d array, be defining an array, and then fill every element of the array with another array, but it does not seem to work.
My current go looks like this:
-(IBAction)alignSequences:(id)sender {
NSString *dnaString1 = @"GAATTCAGTTA";
NSString *dnaString2 = @"GGATCGA";
int intSections = (dnaString1.length+1);
int intRows = (dnaString2.length+1);
//The matrix is initialized, and the value of every element is set to 0
NSMutableArray *horizontalArray = [[NSMutableArray alloc] initWithCapacity:intSections];
for (int i=0; i <= intSections; i++) {
[horizontalArray insertObject:[[NSMutableArray alloc] initWithCapacity:intSections] atIndex:i];
for (int j=0; j <= intRows; j++) {
[[[horizontalArray objectAtIndex:i] objectAtIndex:j] insertObject:[NSNumber numberWithInt:0] atIndex:j];
}
}
NSLog(@"%@",[[horizontalArray objectAtIndex:1] objectAtIndex:1]);
}
Any ideas how to acomplish this? (I’m a newbie to objective-C, so sorry if there are stupid questions or obvious errors in the code)
Yowza! It’s been a while… here goes nothing:
Assuming it works, this is a little cleaner and it should do what you’re attempting without inviting indexing errors. On that note, it looks like you’re initializing your inner array with more space than necessary. This won’t cause an indexing error, but observe:
I think it would be better like this: