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

1 view (last 30 days)
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

Andrei Bobrov
Andrei Bobrov on 6 Sep 2013
Edited: Andrei Bobrov on 9 Sep 2013
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
Quentin Vinckier
Quentin Vinckier on 9 Sep 2013
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 !

Sign in to comment.

More Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 7 Sep 2013
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
Quentin Vinckier
Quentin Vinckier on 9 Sep 2013
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.


Azzi Abdelmalek
Azzi Abdelmalek on 6 Sep 2013
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
Quentin Vinckier
Quentin Vinckier on 6 Sep 2013
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.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!