【问题标题】:Selecting elements from a vector based on condition on another vector根据另一个向量上的条件从一个向量中选择元素
【发布时间】:2019-06-05 13:33:51
【问题描述】:

我想知道如何选择那些与我的预定义数字相对应(即相同位置)的数字。

例如,我有这些向量:

a = [  1 0.1   2   3 0.1 0.5   4 0.1];
b = [100 200 300 400 500 600 700 800]

我需要从b中选择元素,这些元素对应于a中整数的位置(1、2、3和4),所以输出必须是:

output = [1  100
          2  300
          3  400
          4  700]

如何做到这一点?

【问题讨论】:

    标签: arrays matlab vector subset matrix-indexing


    【解决方案1】:

    根据a创建一个逻辑索引,并同时应用到ab,得到想要的结果:

    ind = ~mod(a,1); % true for integer numbers
    output = [a(ind); b(ind)].'; % build result
    

    【讨论】:

      【解决方案2】:
      round(x) == x ----> x is a whole number
      round(x) ~= x ----> x is not a whole number
      
      round(2.4) = 2 ------> round(2.4) ~= 2.4 --> 2.4 is not a whole number
      round(2) = 2 --------> round(2)   == 2 ----> 2 is a whole number
      

      遵循相同的逻辑

      a = [  1 0.1   2   3 0.1 0.5   4 0.1];
      b = [100 200 300 400 500 600 700 800 700];
      iswhole = (round(a) == a);
      output = [a(iswhole); b(iswhole)]
      

      结果:

      output =
      
           1     2     3     4
         100   300   400   700
      

      【讨论】:

      • != 不是有效的 Matlab 语法;改用~=
      【解决方案3】:

      我们可以使用 fix() 函数生成逻辑索引

      ind = (a==fix(a));
      output= [a(ind); b(ind)]'
      

      【讨论】:

        【解决方案4】:

        虽然意图不明确,但为矩阵创建索引是解决方案

        我的解决办法是

        checkint = @(x) ~isinf(x) & floor(x) == x % It's very fast in a big array
        [a(checkint(a))' b(checkint(a))']
        

        这里的关键是创建ab 的索引,它是a 中整数值的逻辑向量。这个函数checkint 可以很好地检查整数。

        检查整数的其他方法可能是

        checkint = @(x)double(uint64(x))==x % Slower but it works fine
        

        checkint = @(x) mod(x,1) == 0 % Slowest, but it's robust and better for understanding what's going on
        

        checkint = @(x) ~mod(x,1) % Slowest, treat 0 as false
        

        它已在许多其他线程中讨论过。

        【讨论】:

        • 很好的方法比较。但是使用最快的方法会因为计算两次而被静音。最好将checkint 的结果保存在临时变量中。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-28
        • 1970-01-01
        • 2022-06-28
        • 1970-01-01
        • 1970-01-01
        • 2014-05-24
        • 1970-01-01
        相关资源
        最近更新 更多