How to convert convert a cell{x,y,...}(V,W) into an array(x,y,...,V,W) with an "automatic process" ?

Dear all,
My problem is the following. I have 1 cell array "cell{x,y,...}(V,W)" with one numeric array (V,W) in each cell {x,y,...} (all of these numeric arrays have the same size and the same dimensions). I need to convert this cell array into a numeric array which have the following "topology": array(x,y,...,V,W). The difficulty is that the conversion "has to be automatic" for any size of the cell array (in other word, it has to work for any number of dimensions x, y, ... and for any number of different values that these dimensions can take). I thought about a lot of ways to code that (with "for" loops and function "eval" or with "cell2mat" function or ...) but it doesn't work. Do you have any idea ?
Thank you in advance,
Quentin

 Accepted Answer

z = cellfun(@(x)randi(26,2,9),cell(3,7,4),'un',0); % Let it be your array
nc = size(z);
nm = size(z{1});
sznew = [nc nm];
zzz = cat(3,z{:});
out = zeros(sznew);
out(:) = zzz;
or
sznew = [nm nc];
zzz = cat(3,z{:});
out = zeros(sznew);
out(:) = zzz;
ADD
s = [size(z), size(z{1})];
x = cat(3,z{:});
out = reshape(permute(x,[3,1,2]),s);

3 Comments

Thank you very much Andrei, that's exactly what I wanted. But I changed just one line to make the code completely automatic: zzz = cat(length(size(a)),z{:}); in place than zzz = cat(3,z{:});
Dear Andrei, finally, this code doesn't work because it mixes all the numbers in the numeric array. The version of Azzi just below works well. But thank you for your answer !
Hi Quentin! See ADD part in my answer - here other variant

Sign in to comment.

More Answers (2)

v=2;
w=9;
tic
n=[size(a) v w];
out1=zeros(n);
idx1= repmat({':'},1,ndims(a));
for k=1:v
for p=1:w
idx= [idx1 {k} {p}];
out1(idx{:})=cellfun(@(x) x(k,p),a);
end
end
% But the result is different from Andrei's result

1 Comment

Thank you Azzi, finally, the code of Andrei doesn't work because it mixes all the numbers in the numeric array. Your code just above works and it's a complete automatic version :) Thanks a lot for that !

Sign in to comment.

v=2;
w=9;
n=[size(a) v w];
out=zeros(n);
for k=1:v
for p=1:w
out(:,:,:,k,p)=cellfun(@(x) x(k,p),a);
end
end
disp(out)

1 Comment

Thank you Azzi for your answers but I will finely use the code of Andrei. Your code works but I wanted to have a completely automatic one (if you don't know how many dimensions they are in "a", we can not do the conversion with your code because we need to write out(:,:,:,k,p)...)

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!