Here's a little trick using num2cell
, which actually works with cell array inputs – the key is to first expand C
into a 5-by-2 cell array (equivalent to cell(5,2)
).
% Your example to produce C
uc = ['A':'Z'];
randstr = @() uc(randi(26, [1 4]));
M = 5;
rng(0); % Keep example reproducible
C = arrayfun(@(i) {randstr() i}, 1:M, 'un', 0)';
% D = num2cell(reshape([C{:}],[N M]).',[1 M])
D = num2cell(reshape([C{:}],[size(C{1},2) size(C,1)]).',[1 size(C,1)])
or more simply
D = num2cell(cat(1,C{:}),1)
where D{:}
returns:
ans =
'VXDX'
'QCHO'
'YZEZ'
'YMUD'
'KXUY'
ans =
[1]
[2]
[3]
[4]
[5]
The inverse operation to go from D
back to C
can be accomplished via:
% C = num2cell(reshape([D{:}],[N M]),[M N])
C = num2cell(reshape([D{:}],[size(D{1},1) size(D,2)]),[size(D,2) size(D{1},1)])
or
C = num2cell(cat(2,D{:}),2)
Thus you might be able to create a function like the following that would work in either direction:
transpose_cells = @(C)num2cell(cat(isrow(C)+1,C{:}),isrow(C)+1);
isequal(transpose_cells(transpose_cells(C)),C)