Extracting a specific element from each cell within cell array

前端 未结 3 704
轻奢々
轻奢々 2021-01-21 01:24

I have a cell array A of size 10x10 (say). Each cell in turn contains a 5x20 matrix. I want to select (i,j) element from each

3条回答
  •  梦谈多话
    2021-01-21 02:23

    The easy to use cellfun one-liner would be:

    ii = 2;
    jj = 1;
    A = {[1 2;5 6], [3 4; 6 7]; [3 4; 6 7], [9 8; 5 6]};
    
    B = cell2mat( cellfun( @(x) x(ii,jj), A, 'uni', 0) )
    

    gives:

    B =
    
         5     6
         6     5
    

    Advantage over Divakar's Solution: it works also for inconsistent matrix sizes in A.

    And if you want to avoid also the outer loop, another fancy two-liner:

    dim = [2 2];
    [II, JJ] = meshgrid( 1:dim(1), 1:dim(2) );
    
    C = cellfun( @(y) ...
        { cell2mat( cellfun( @(x) x( real(y), imag(y) ), A, 'uni', 0) ) },...
          num2cell( II(:)+1i*JJ(:) ))
    

    gives:

    >> celldisp(C)
    
    C{1} =            % ii = 1 , jj = 1
    
         1     3
         3     9
    
    
    
    C{2} =            % ii = 1 , jj = 2
    
         2     4
         4     8
    
    
    
    C{3} =            % ii = 2 , jj = 1
    
         5     6
         6     5
    
    
    
    C{4} =            % ii = 2 , jj = 2
    
         6     7
         7     6
    

提交回复
热议问题