Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: index a cell array with cell array of arrays and return a cell array

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.

like image 340
reve_etrange Avatar asked Mar 18 '11 08:03

reve_etrange


People also ask

How do you index a cell in an array cell in MATLAB?

There are two ways to refer to the elements of a cell array. Enclose indices in smooth parentheses, () , to refer to sets of cells--for example, to define a subset of the array. Enclose indices in curly braces, {} , to refer to the text, numbers, or other data within individual cells.

How do you return the index of an array element in MATLAB?

To find the index of the element in the array, you can use the find() function. Using the find() function you can find the indices and the element from the array. The find() function returns a vector containing the data.

How do you turn a cell array into an array?

A = cell2mat( C ) converts a cell array into an ordinary array. The elements of the cell array must all contain the same data type, and the resulting array is of that data type. The contents of C must support concatenation into an N-dimensional rectangle.


1 Answers

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.

like image 68
gnovice Avatar answered Sep 29 '22 10:09

gnovice