MATLAB:使用数组的单元格数组索引并返回一个单元格数组。

6
我有一个(n X 1)向量的单元数组A,以及一个包含对A索引的向量的单元数组B。我想提取一个单元数组C,使得C{i} = [A{B{i}}]。 换句话说,我有一个索引数组的数组单元,并且我想提取与每个索引数组对应的A中向量连接的矩阵。
for i = 1:length(B)
    %# B{i} is an array of indices, C{i} is a matrix
    C{i} = [ A{ B{i} } ];
end

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

我只用索引表达式就能做到吗?或者至少不用循环就能实现吗? 我认为deal()可能需要参与其中,但是无法想出方法。
2个回答

6

这里有两个备选方案:

  • 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);
    

最终,我会根据速度和可读性来决定使用哪种解决方案,实际上可能会选择您基于for循环的解决方案。


+1 很好,摆脱了“UniformOutput”,“false”。真是一件让人头疼的事情。 - Andrew Janke

0

这个表达式会创建一个单元数组,其中每个元素都是来自 A 的单个向量。我想要创建一个单元数组,其中每个元素都是由来自 A 中对应于 B 元素中的索引的向量组成的矩阵。 - reve_etrange

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接