6

Say I have a cell array of (n X 1) vectors, A, and a cell array of vectors containing indices into A, called B. I wish to extract a cell array, C, such that C{i} = [A{B{i}}].
In other words, I have a cell array of arrays of indices, and I want to pull out the matrices corresponding to the concatenations of the vectors in A indexed by each of those arrays of indices.

for i = 1:length(B)
    %# B{i} is an array of indices, C{i} is a matrix
    C{i} = [ A{ B{i} } ];
end

The loop is equivalent to:

C = cellfun(@(x)[A{x}],B,'UniformOutput',false); %# implicit for loop w/ closure

Can I do that using an indexing expression alone? Or at least without the loop?
I think deal() might have to be involved but can't figure it out.

Jonas Stein
  • 6,826
  • 7
  • 40
  • 72
reve_etrange
  • 2,561
  • 1
  • 22
  • 36

2 Answers2

6

Here are two alternative solutions:

  • Collect all the indices of B together with the function cell2mat, index the contents of A to make one large matrix, then divide that matrix up using the function mat2cell and the sizes of the index arrays in B:

    N = size(A{1});                        % Size of an array in A
    M = cellfun('prodofsize', B);          % Array of sizes of elements in B
    C = mat2cell([A{cell2mat(B)}], N, M);
    
  • Here's a more compact version of your cellfun-based solution:

    C = cellfun(@(x) {[A{x}]}, B);
    

Ultimately, I would decide what solution to use based on speed and readability, which may actually turn out to be your for-loop-based solution.

gnovice
  • 125,304
  • 15
  • 256
  • 359
0

Try the following expression:

C = A(cell2mat(B))

You may have a look at Loren's blog post about Cell Arrays and Their Contents

zellus
  • 9,617
  • 5
  • 39
  • 56
  • This expression makes a cell array with each element a single vector from `A`. I want to create a cell array with each element a matrix composed of vectors from `A` corresponding to the indices in an element of `B`. – reve_etrange Mar 18 '11 at 09:17