# How to convert a 1xn cell array composed of 1D arrays to a higher dimensional (nested) cell array?

조회 수: 21 (최근 30일)
Travis Briles 2021년 4월 12일
답변: Srivardhan Gadila 2021년 4월 17일
I have a 1xn cell array called 'XX' that is generated in a loop where each of the 'n' entries is a 1D array. Due to the details of the calculation the value of 'n' can vary and the length of each elemeent in the array can be different. For concreteness, suppose that one output of the loop gives the cell below.
a= [185.0714 186.1008 187.1303 188.1597 189.1890 190.2185 191.2478 192.2772 193.3066 194.3359 195.3653 195.7647].';
b= [185.5117 186.5077 187.5037 188.4993 189.4949 190.4903 191.4855 192.4806 193.4760 194.4710 195.4662].';
n=2;
XX=cell(1,n)
XX{1} = a;
XX{2}=b;
I would like to convert this cell array 'XX{i}' to a higher dimensional cell array 'YY{i,k}' where 'i' still refers to the cell array as above and 'k' refers to the index of the 'k-th' element in XX{i}.
I realize that I can refer to the element I need from XX as XX{i}(k) but I would like it to be a cell array because I need to build new cell arrays off of YY{i,k}. How do I do with with a for loop?
............
This solution is partway there but iI don't think it's really a nested cell array.
for i=1:n
for k = 1:length(XX{i})
YY{k,i} = XX{i}(k)
end
end
This appears to basically work but it seems clunky. If I wanted to access the array stored in the 'first column' I could use
getFIRSTcolumn = [YY{:,1}].' %identical to XX{1} above.
Is there a slicker way to do this?

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

### 채택된 답변

I think above code is the simple and easiest way to do it.
You can also do it as follows:
M = max(cellfun(@numel, XX));
y = cell(M,n);
for i=1:n
k = length(XX{i});
y(1:k,i) = num2cell(XX{i});
end
You can also try other ways by making use of the following functions: num2cell, mat2cell, cellfun and other functions listed in Cell Arrays documentation.

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

### 카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by