0

I have a cell array, lets say C. Each cell contains a matrix.

For example lets say C is

C{1}=[1 2;3 4;5 6]
C{2}=[7 8;9 10;11 12]

How can I create a new cell array D, whose i-th element is a matrix consisted by the i-th transposed rows of all matrices in C?

Then D must be

D{1}=[1 7;2 8]
D{2}=[3 9;4 10]
D{3}=[5 11;6 12]
HebeleHododo
  • 3,620
  • 1
  • 29
  • 38
Chris
  • 167
  • 5

2 Answers2

1

A slightly less clumsy solution:

C{1}=[1 2;3 4;5 6]
C{2}=[7 8;9 10;11 12]

tmp = cat(3,C{:});
tmp = permute(tmp, [3 2 1]) %# now every slice is of the right form
szTmp = size(tmp);
D = mat2cell(tmp,szTmp(1),szTmp(2),ones(szTmp(3),1)))
Jonas
  • 74,690
  • 10
  • 137
  • 177
0

Given that C is always of the size you have specified, you can try the following rather clumsy solution:

C{1}=[1 2;3 4;5 6]
C{2}=[7 8;9 10;11 12]


tmp = reshape( [C{:}]', 2,2,3);

D = arrayfun(@(x) squeeze(tmp(:,:,x)), 1:3, 'UniformOutput',  false);

This results in

>> D{:}

ans =

     1     7
     2     8


ans =

     3     9
     4    10


ans =

     5    11
     6    12

For matrices of arbitrary size, you can use

n = length(C);
[q,p] = size(C{1});

tmp = reshape( [C{:}]', p, n, q);

D = arrayfun(@(x) squeeze(tmp(:,:,x)), 1:n, 'UniformOutput',  false);
H.Muster
  • 9,297
  • 1
  • 35
  • 46
  • Thank you a lot! This works perfectly but i dont know what should i change in the reshape and in squeeze functions if my number of elements in C are n and the matrices in each cell are of size p-by-q. – Chris Jan 30 '13 at 16:50
  • @Christos: just replace 3 by `n` and the 2's by `p` and `q`. Also, you may want to have a look at my solution. – Jonas Jan 30 '13 at 16:55