user1809923
user1809923

Reputation: 1255

Find ONE value that is in A but not in B

Assuming I have

A = [1 2 3 4 5 6 7 8 9 10];
B = [1 2 4 5 8];

I want to find ONE value that is in A but not in B. I could do the following:

temp  = setdiff(A,B);
if ~isempty(temp)
  myValue = temp(1);
else
  myValue = [];
end

But is there a faster way, since I only need ONE value and not all of them? Efficiency is important :)

Upvotes: 2

Views: 80

Answers (2)

Jonas
Jonas

Reputation: 74940

Since A is 1:n, the first value of B that is not in A is where the difference between sorted elements of B is bigger than 1.

sortedB = sort(B);

firstMissingValue = find(diff([0,sortedB,size(A,1)])>1,1,'first');

Upvotes: 3

Clemens
Clemens

Reputation: 245

Maybe try that? For me it was faster, maybe you can try it.

a=ismember(A,B); 
if sum(a)~=0
   myValue = A(a);
   myValue = myValue(1);
else
   myValue =  [];
end

Upvotes: 0

Related Questions