我在尝试解决这个问题时碰壁了:
给定一个包含 n 个元素数组的索引向量的 5x1 元胞数组,我需要找到反向映射。
我得到的是关系“在第 2 组中,有元素 15、16、17,...” 我想要的是“元素 15 是组 2、4、5 的成员。”
这是我的元胞数组的结构
myCellArray =
[1x228 double]
[1x79 double]
[1x136 double]
[1x93 double]
[1x81 double]
这是我索引向量的部分内容
myCellArray{2}(1:5) =
15 16 17 18 19
我想要的是一个包含 n 个单元格的单元格数组,其中包含每个元素的组成员资格索引。
帮助?
最佳答案
您可以结合使用 cellfun
和 arrayfun
来做到这一点。首先创建一个元胞数组:
>> mycellarray = { [1 2], [4 5], [3 4], [1 2 3 4 5] };
要获取包含特定数字(比如 1)的元胞数组元素,您可以使用 cellfun
:
>> find( cellfun(@(s)ismember(1, s), mycellarray) )
ans =
1 4
它告诉您 1 在 mycellarray
的第 1 个和第 4 个元素中。现在您可以使用 arrayfun
将其映射到所有可能索引的列表中。生成的数组长度可能不同,因此我们需要将 'UniformOutput'
设置为 false
。
>> n = 5;
>> result = arrayfun(@(i)find(cellfun(@(s)ismember(i,s), mycellarray)), 1:n, ...
'UniformOutput', false);
元素是你想要的索引向量--
>> result{1}
ans =
1 4 # since 1 is in the 1st and 4th array
>> result{3}
ans =
3 4 # since 3 is in the 3rd and 4th array
关于matlab - 在 MATLAB 索引元胞数组中反向查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14934796/