【问题标题】:Mapping An Array To Logical Array In Matlab在 Matlab 中将数组映射到逻辑数组
【发布时间】:2017-09-15 14:35:13
【问题描述】:

假设一个array a=[1,3,8,10,11,15,24]和一个logical array b=[1,0,0,1,1,1,0,0,0,1,1,1,1,1],如何得到[1,1,3,1,3,8,1,3,8,1,2,3,8,10],看看b中逻辑在哪里变成1,a的数组索引重置,所以它从头开始,也是相同的逻辑变为 0 a array 从头开始​​并继续为 1,3,8,10..etc.

【问题讨论】:

    标签: arrays matlab indexing


    【解决方案1】:

    您可以使用diff 查找b 更改的位置,然后使用arrayfuna 生成索引:

    a=[1,3,8,10,11,15,24];
    b=[1,0,0,1,1,1,0,0,0,1,1,1,1,1];
    idxs = find(diff(b) ~= 0) + 1; % where b changes
    startidxs = [1 idxs];
    endidxs = [idxs - 1,length(b)];
    % indexes for a
    ia = cell2mat(arrayfun(@(x,y) 1:(y-x+1),startidxs,endidxs,'UniformOutput',0));
    res = a(ia);
    

    【讨论】:

      【解决方案2】:

      您可以使用 for 循环并跟踪 b 数组的状态(01):

      a = [1,3,8,10,11,15,24];
      b = [1,0,0,1,1,1,0,0,0,1,1,1,1,1];
      
      final = []
      index = 0;
      state = b(1);
      for i = 1:numel(b)
          if b(i) ~= state
              state = b(i);
              index = 1;
          else
              index = index+1;
          end
              final = [final, a(index) ];
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-21
        • 2016-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多