Reverse Lookup in MATLAB Cell Array

I hit a brick wall trying to solve this problem:

Given an array of 5x1 cells of index vectors for an array of n elements, I need to find the inverse mapping.

I have a relationship โ€œThere are elements 15, 16, 17, .... in group 2,โ€ I want โ€œElement 15 to be a member of group 2,4,5.โ€

This is the structure of my cell array

myCellArray = [1x228 double] [1x79 double] [1x136 double] [1x93 double] [1x81 double] 

This is part of the contents of my index vector.

 myCellArray{2}(1:5) = 15 16 17 18 19 

I need an array of cells of n cells containing group membership indices for each element.

help?

+4
source share
2 answers

You can do this with a combination of cellfun and arrayfun . First create an array of cells:

 >> mycellarray = { [1 2], [4 5], [3 4], [1 2 3 4 5] }; 

To get the elements of an array of cells that contain a specific number (e.g. 1), you can use cellfun :

 >> find( cellfun(@(s)ismember(1, s), mycellarray) ) ans = 1 4 

Which tells you that 1 is in the 1st and 4th elements of mycellarray . Now you can simply match this over a list of all possible indexes using arrayfun . Arrays created can have different lengths, so we need to set 'UniformOutput' to false .

 >> n = 5; >> result = arrayfun(@(i)find(cellfun(@(s)ismember(i,s), mycellarray)), 1:n, ... 'UniformOutput', false); 

Elements are the index vectors you want -

 >> 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 
+5
source

Do you need to use array cells to save space?

Otherwise, you can change your current matrix to the normal matrix MxN, where N is n, as you defined, and M is the number of groups. And then just strip the end of each line with zeros. Thus, it contains the same information, but makes your return request simple using find .

therefore, if n = [1 2 3 4 5 6 7]

and we have 3 groups for which group 1 [1 4 5] , group 2 is [3] , and group 3 is [1 2 6 7] , your current matrix will be

 M = 3; N = numel(n); m = zeros(M,N); m(1, 1:3) = [1 4 5]; m(2, 1) = 3; m(3, 1:4) = [1 2 6 7]; 

Now you want to know which group the number i belongs to. It's that simple (updated based on Chris Taylor's observation)

 find(any(m == i, 2)) 
+4
source

All Articles