Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transpose a matrix in Objective c?

i have a 2d matrix. how can i transpose it in objective c?

have i use nested loop to transpose it as i failed to find any method in array and mutablearray classes.

My matix is of 3x3.

NSMutableArray *row1=[NSMutableArray arrayWithObjects:@1,@2,@3, nil];
NSMutableArray *row2=[NSMutableArray arrayWithObjects:@4,@5,@6, nil];
NSMutableArray *row3=[NSMutableArray arrayWithObjects:@7,@8,@9, nil];

NSMutableArray *twoDArray=[NSMutableArray arrayWithObjects:row1,row2,row3, nil];
NSLog(@"%@",twoDArray);

what to do after this?


1 Answers

It's easy as that:

NSMutableArray *result = [NSMutableArray arrayWithCapacity:3];

for (NSUInteger i = 0; i < 3; i++) {
    [result addObject:@[row1[i], row2[i], row3[i]]];
}

I assumed it will always be 3x3 matrix, for simplicity.

like image 185
Adam Avatar answered Nov 19 '25 10:11

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!