Reputation: 33
I am trying to find a more efficient way of finding the index of an array within a cellarray other than using 'for' loops. My problem is as follows:
a = [6,3]
b = {[1,10];[1,8,10];[8,10];[2,8];2;[2,4,5];[2,4];[];[3,6];[3,4,6];6;[3,5,6];[6,9];[1,6,9];[1,6,7,9]}
I need to find the index of 'a' within 'b'. My current method works but is quite slow and cumbersome when you increase the size of 'b' which is my case. I'm not interested in the order of the array, only that the contents are the same which is why I use the 'setxor' method. The code below shows an example of how I currently do this.
for num = 1:size(b,1)
new_array(num,1) = isempty(setxor(a, b{num,1}));
if (new_array(num,1) == 1)
indexOfArray = num;
break;
end;
end;
Is there a better way of doing this? Thanks in advance, Vincent
Upvotes: 3
Views: 147
Reputation: 112749
It's easy with cellfun
:
find(cellfun(@(x) isempty(setxor(a,x)), b))
If you only want the first coincidence, use
find(cellfun(@(x) isempty(setxor(a,x)), b), 1)
This uses your definition of coincidence, in terms of setxor
.
Thanks to @Dan and @DennisJaheruddin for their constructive comments, which have been incorporated into this answer.
Upvotes: 5