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

24 views (last 30 days)
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?
............
Partial Answer
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?

Accepted Answer

Srivardhan Gadila
Srivardhan Gadila on 17 Apr 2021
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.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!