TyanTowers
TyanTowers

Reputation: 160

Find index of smallest element in an array not in another array (Matlab)

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!

Upvotes: 1

Views: 85

Answers (2)

Eugene Sh.
Eugene Sh.

Reputation: 18361

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

Upvotes: 1

Sam Roberts
Sam Roberts

Reputation: 24127

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.

Upvotes: 1

Related Questions