3

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

2
  • 3
    What do you mean with 'contents are the same'? Is [1 1 1 1 2] the same as [2 1] ? Otherwise you may need to sort them first and then check for full equality. Commented Oct 7, 2013 at 15:53
  • No, those two arrays have the same values but not the same contents. I mean in the sense where [1 2 3], [1,3,2], [3,2,1] etc... all have identical contents though not in the same order. Commented Oct 7, 2013 at 17:09

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

10 Comments

Probably stick with isempty(setxor(a,x)) over isequal
@Dan Well, I've tested a bit and isequal seems to be faster
The 'first' addition is not required as it is the default setting.
@LuisMendo you could do sort(a) and still have decent performance. But that might not be a general solution. It looks like it is though based on the example data
You said you want to match a and b without regard to order. However, if each vector in b is ordered, as in your example, you can sort a at the beginning (a = sort(a)) and then use isequal(a,x) instead of isempty(setxor(a,x)). That will save time
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.