I have hit a brick wall trying to solve this:
Given a 5x1 cell array of vectors of indices to an array of n elements I need to find the reverse mapping.
What I have is the relation "In group 2, there are elements 15, 16, 17,...." What I want to have is "Element 15 is 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
What I want is a cell array of n cells containing the indices of group membership for each element.
help?
You can do this with a combination of cellfun
and arrayfun
. First create a cell array:
>> mycellarray = { [1 2], [4 5], [3 4], [1 2 3 4 5] };
To get the elements of the cell array that contain a particular number (say 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 just map this over the list of all possible indexes using arrayfun
. The arrays that are produced might be of different length, so we need to set 'UniformOutput'
to false
.
>> n = 5;
>> result = arrayfun(@(i)find(cellfun(@(s)ismember(i,s), mycellarray)), 1:n, ...
'UniformOutput', false);
The elements are the index vectors that 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With