Extract only some specific elements of the arrays of a cell

21 views (last 30 days)
I have a cell, say C, where each array is also a cell. I have an index set and I want to extract cells 2, 5,1. It can be done by using . But it returns a cell where each cell is still a cell. What I want to know is how I can extract a new cell that contains cells 2,5, and 1 of the original cell, and also for each individual cell, it only contains cells 2,5, and 1. Therefore, the final cell is a cell and all individual cells are also a cell.

Accepted Answer

Stephen23
Stephen23 on 5 Apr 2022
C = arrayfun(@(n)num2cell(rand(1,5)),1:5,'uni',0)
C = 1×5 cell array
{1×5 cell} {1×5 cell} {1×5 cell} {1×5 cell} {1×5 cell}
C{:}
ans = 1×5 cell array
{[0.0326]} {[0.4440]} {[0.0083]} {[0.6590]} {[0.0110]}
ans = 1×5 cell array
{[0.2557]} {[0.8965]} {[0.0137]} {[0.0078]} {[0.5929]}
ans = 1×5 cell array
{[0.4589]} {[0.6418]} {[0.2742]} {[0.3274]} {[0.1927]}
ans = 1×5 cell array
{[0.9374]} {[0.0589]} {[0.0613]} {[0.5019]} {[0.8903]}
ans = 1×5 cell array
{[0.6602]} {[0.0461]} {[0.6398]} {[0.9363]} {[0.9559]}
X = [2,5,1];
D = cellfun(@(d)d(X),C(X),'uni',0)
D = 1×3 cell array
{1×3 cell} {1×3 cell} {1×3 cell}
D{:}
ans = 1×3 cell array
{[0.8965]} {[0.5929]} {[0.2557]}
ans = 1×3 cell array
{[0.0461]} {[0.9559]} {[0.6602]}
ans = 1×3 cell array
{[0.4440]} {[0.0110]} {[0.0326]}

More Answers (1)

KSSV
KSSV on 5 Apr 2022
C = cell(5,1) ;
for i = 1:5
C{i} = rand(1,3) ;
end
idx = [2 5 1] ;
iwant = C(idx)
iwant = 3×1 cell array
{[0.2284 0.3773 0.9742]} {[0.5814 0.1525 0.4597]} {[0.9464 0.0561 0.6506]}
  1 Comment
Hamed Jalali
Hamed Jalali on 5 Apr 2022
Each element of C is also a cell. If you cahnge C{i} = rand(1,3) ; to C{i} = rand(1,5) ; your final cell, iwant is a cell which each element is still double. I need all elements of the final cell be a cell/double.

Sign in to comment.

Categories

Find more on Multidimensional Arrays 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!