Star
Star

Reputation: 2299

How to cut a matrix in Matlab?

I would like to transform the matrix A into the matrix B without using cells (e.g. mat2cell) in Matlab, where

A=[1 2 3; 
   4 5 6; 
   7 8 9; 
   10 11 12; 
   13 14 15; 
   16 17 18; 
   19 20 21; 
   22 23 24; 
   25 26 27];

B=[1 2 3 10 11 12 19 20 21;
   4 5 6 13 14 15 22 23 24; 
   7 8 9 16 17 18 25 26 27];

Upvotes: 2

Views: 1088

Answers (2)

Divakar
Divakar

Reputation: 221574

All you need is some reshape + permute magic -

N = 3;  %// Cut after every N rows and this looks like the no. of columns in A
B = reshape(permute(reshape(A,N,size(A,1)/N,[]),[1 3 2]),N,[])

Upvotes: 2

Luis Mendo
Luis Mendo

Reputation: 112679

This builds a linear index to rearrange the entries of A and then reshapes into the desired matrix B:

m = 3; %// cut size in rows of A. Assumed to divide size(A,1)
n = size(A,2);
p = size(A,1);
ind = bsxfun(@plus, ...
      bsxfun(@plus, (1:m).', (0:n-1)*p), permute((0:p/m-1)*m, [1 3 2]));
B = reshape(A(ind(:)), m, [])

Upvotes: 0

Related Questions