将多维数组拆分为较小的多维数组

时间:2015-10-11 15:14:49

标签: objective-c multidimensional-array linear-algebra

我有一个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] ]

在我的实际程序中,矩阵包含对象,而不是值。我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

试试这个:

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);