How to convert a 1xn cell array composed of 1D arrays to a higher dimensional (nested) cell array?
    14 ビュー (過去 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?
............
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?  
0 件のコメント
採用された回答
  Srivardhan Gadila
    
 2021 年 4 月 17 日
        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.
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
				Help Center および File Exchange で Logical についてさらに検索
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!