我试图解决这个问题:
给定n个元素数组的索引向量的5x1单元阵列,我需要找到反向映射.
我所拥有的是关系"在第2组中,有元素15,16,17 ......"我想要的是"元素15是2,4,5组的成员".
这是我的单元格数组的结构
myCellArray =
[1x228 double]
[1x79 double]
[1x136 double]
[1x93 double]
[1x81 double]
Run Code Online (Sandbox Code Playgroud)
这是我的索引向量的一部分内容
myCellArray{2}(1:5) =
15 16 17 18 19
Run Code Online (Sandbox Code Playgroud)
我想要的是一个包含每个元素的组成员资格索引的n个单元格的单元格数组.
救命?
你可以结合使用cellfun和arrayfun.首先创建一个单元格数组:
>> mycellarray = { [1 2], [4 5], [3 4], [1 2 3 4 5] };
Run Code Online (Sandbox Code Playgroud)
要获取包含特定数字(例如1)的单元格数组元素,您可以使用cellfun:
>> find( cellfun(@(s)ismember(1, s), mycellarray) )
ans =
1 4
Run Code Online (Sandbox Code Playgroud)
这告诉你1是在第1和第4个元素mycellarray.现在,您可以使用,将其映射到所有可能索引的列表上arrayfun.生成的数组可能长度不同,因此我们需要设置'UniformOutput'为false.
>> n = 5;
>> result = arrayfun(@(i)find(cellfun(@(s)ismember(i,s), mycellarray)), 1:n, ...
'UniformOutput', false);
Run Code Online (Sandbox Code Playgroud)
元素是您想要的索引向量 -
>> 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
Run Code Online (Sandbox Code Playgroud)