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

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2013년 9월 6일
편집: Andrei Bobrov 2013년 9월 9일
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

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

댓글을 달려면 로그인하십시오.

추가 답변 (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

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 !

댓글을 달려면 로그인하십시오.

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

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)...)

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by