在不在另一个数组中的数组中查找最小元素的索引(Matlab)
Find index of smallest element in an array not in another array (Matlab)
我有一个数组 a = [6 8 2 1 9] 和 b = [1 2 6]。我想要一个 returns 2 的函数,因为 a(2)=8 是 a 不在 b 中的最小元素。
到目前为止我尝试过的:
[A,I] = sort(a);
index = I(find(~ismember(A,b),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
这会找到您请求的索引,而不是第一个答案给出的值。
另一个(我相信更快)解决方案是:
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
我有一个数组 a = [6 8 2 1 9] 和 b = [1 2 6]。我想要一个 returns 2 的函数,因为 a(2)=8 是 a 不在 b 中的最小元素。
到目前为止我尝试过的:
[A,I] = sort(a);
index = I(find(~ismember(A,b),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
这会找到您请求的索引,而不是第一个答案给出的值。
另一个(我相信更快)解决方案是:
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