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)
Show older comments
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
1 Comment
Accepted Answer
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
More Answers (2)
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
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)
See Also
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!