查找不在另一个数组中的数组中最小元素的索引(Matlab)

时间:2015-03-06 15:23:45

标签: arrays matlab sorting find

我有一个数组a = [6 8 2 1 9]和b = [1 2 6]。我想要一个函数,它返回2,因为a(2)= 8,这是b中not的最小元素。

到目前为止我尝试过:

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

我想要更快的东西,因为这段代码必须运行很多次并且涉及的数组非常大。

提前致谢!

2 个答案:

答案 0 :(得分:1)

这可以满足您的需求吗?

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

编辑:

哎呀 - 我的意思是

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

这会根据您的请求找到索引,而不是第一个答案给出的值。

答案 1 :(得分:1)

另一个(更快,我相信)解决方案将是:

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
相关问题