MATLAB: index a cell array with cell array of arrays and return a cell array
Here are two alternative solutions:
-
Collect all the indices of
B
together with the functioncell2mat
, index the contents ofA
to make one large matrix, then divide that matrix up using the functionmat2cell
and the sizes of the index arrays inB
: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.
reve_etrange
Updated on August 10, 2022Comments
-
reve_etrange over 1 year
Say I have a cell array of (n X 1) vectors,
A
, and a cell array of vectors containing indices intoA
, calledB
. I wish to extract a cell array,C
, such thatC{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 inA
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 thinkdeal()
might have to be involved but can't figure it out.