【问题标题】:Find index of smallest element in an array not in another array (Matlab)查找数组中最小元素的索引而不是另一个数组(Matlab)
【发布时间】:2015-03-06 15:23:45
【问题描述】:

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

到目前为止我所尝试的:

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

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

提前致谢!

【问题讨论】:

  • 总是2个数组吗?只需使用setdiff

标签: arrays matlab sorting find


【解决方案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

【讨论】:

    【解决方案2】:

    这能满足你的需要吗?

    >> 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
    

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

    【讨论】:

      猜你喜欢
      • 2019-01-12
      • 2016-09-24
      • 1970-01-01
      • 2013-07-19
      • 2018-10-17
      • 2012-07-19
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      相关资源
      最近更新 更多