访问元胞数组中数组的简单方法

Simple way of accessing arrays in cell arrays

我正在寻找一种快速、简单的方法来访问元胞数组中的特定数组。例如,假设我有

A = rand(10,2);
B = rand(15,1);
C = rand(130,1);
D = rand(16,1);
E = rand(1000,25);
my_cell = {A,B,C,D,E};

假设我只想在新元胞数组中包含第 1、第 2 和第 4 个矩阵(即 A、B 和 D)。因此,新元胞数组将由 {A, B, D} 组成。使用 for 循环显然很容易:

idx=[1,2,4];
new_cell=cell(1,length(idx));
for i=1:length(idx)
   new_cell{i}=my_cell{idx(i)};
end

我想知道是否有偶 quicker/simpler 方法。也许有一个我不知道的明显的索引技巧或功能?我将不胜感激。

是的,您可以像普通数组一样为元胞数组编制索引(即使用括号而不是方括号)。实际上,它 一个 "normal" 数组:它是 "cell" 元素的普通数组。所以像普通数组一样索引它们只是 returns 个人 "cell elements" 而不是他们的 contents.

因此你可以做到

my_cell(idx)


编辑: 只是为了明确 "indexing a cell like an array" 和 "collecting the comma-separated-output into a new cell array" 方法之间的区别:

>> my_cell = {'A','B','C'; 'D','E','F'; 'G', 'H', 'I'}    
my_cell = 
    'A'    'B'    'C'
    'D'    'E'    'F'
    'G'    'H'    'I'

>> my_cell(1:2,1:2)
ans = 
    'A'    'B'
    'D'    'E'

>> {my_cell{1:2,1:2}}  % this will ALWAYS be a horizontal cell vector
ans = 
    'A'    'D'    'B'    'E'

{my_cell{idx}} 应该可以解决问题。

my_cell{idx} returns my_cell 中的元素由 idx 索引为 逗号分隔列表 。相当于A, B, D。您需要做的就是使用 {} 关闭此列表,以从中创建元胞数组。