我有一个2D值数组(比如4x4矩阵),我想把它分解成更小的子2D数组。
NSArray *xArr = @[
@[1, 2, 3, 4],
@[5, 6, 7, 8],
@[9, 10, 11, 12],
@[13, 14, 15, 16]
];
NSArray splitArr = [xArr splitArrayBy:4]; // xArr has 16 members, so return an array with four 2D arrays
// splitArr = @[
// @[ @[1, 2], @[5, 6] ],
// @[ @[3, 4], @[7, 8] ],
// @[ @[9, 10], @[13, 14] ],
// @[ @[11, 12], @[15, 16] ]
// ];
我很难把它分解成一个可以完成这个的循环。MatLab中有一个函数可以在mat2cell中完成此操作。
- (NSArray *) splitArrayBy:(NSUInteger)num {
// NOTE: I'm not using the value passed in, just assuming it's a 4x4 matrix
NSMutableArray *groupedArray = [NSMutableArray array];
for (int i = 0; i < 4; i = i + 2) {
NSMutableArray *temp = [NSMutableArray array];
for (int row = i; row < i + 2; row++) {
NSMutableArray *rowArr = [NSMutableArray array];
for (int col = i; col < i + 2; col++) {
[rowArr addObject:self.pixelData[row][col]];
}
[temp addObject:rowArr];
}
[groupedArray addObject:temp];
}
return groupedArray;
}
这显然是错误的算法,因为它只给我第一个和最后一个子数组(@[ @[1, 2], @[5, 6] ], @[ @[11, 12], @[15, 16] ]
)
在我的实际程序中,矩阵保存对象,而不是值。我遗漏了什么?
试一下:
NSArray *xArr = @[
@[@1, @2, @3, @4],
@[@5, @6, @7, @8],
@[@9, @10, @11, @12],
@[@13, @14, @15, @16]
];
NSMutableArray *twoDArray = [NSMutableArray array];
NSMutableArray *twoDArray1 = [NSMutableArray array];
NSMutableArray *twoDArray2 = [NSMutableArray array];
for (NSArray *array in xArr) {
NSArray *subArray1 = [array subarrayWithRange:NSMakeRange(0, 2)];
NSArray *subArray2 = [array subarrayWithRange:NSMakeRange(2, 2)];
[twoDArray1 addObject:subArray1];
[twoDArray2 addObject:subArray2];
// Now reset the objects after saving them
if (twoDArray1.count == 2) {
[twoDArray addObject:[twoDArray1 copy]];
[twoDArray addObject:[twoDArray2 copy]];
[twoDArray1 removeAllObjects];
[twoDArray2 removeAllObjects];
}
}
NSLog(@"twoDArray = %@", twoDArray);