1

I have an array a = [6 8 2 1 9] and b = [1 2 6]. I want a function which returns 2 since a(2)=8 which is the smallest element of a not in b.

What I have tried so far:

[A,I] = sort(a); 
index = I(find(~ismember(A,b),1))

I would like something faster as this piece of code has to run many times and the arrays involved are very large.

Thanks in advance!

1
  • 1
    is it always 2 arrays? Just use setdiff Commented Mar 6, 2015 at 15:25

2 Answers 2

1

Another (faster, I believe) solution would be:

a = [6 8 2 1 9];
b = [1 2 6];
[d,I] = setdiff(a,b); % d is the set difference, I is the indices of d elements in a
[m,J] = min(d);       % m is the minimum in d, J is it's index 
I(J)                  % This is the index of m in d (the value that you want)
ans = 
     2
Sign up to request clarification or add additional context in comments.

Comments

1

Does this do what you need?

>> a = [6 8 2 1 9];
>> b = [1 2 6];
>> min(a(~ismember(a,b)))
ans =
     8

Edit:

Oops - I meant

>> find(a==min(a(~ismember(a,b))),1)
ans =
     2

This finds the index as you requested, rather than the value, which the first answer gives.

Comments

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.