【问题标题】:Mapping elements in vector to related, but larger vector将向量中的元素映射到相关但更大的向量
【发布时间】:2018-09-28 11:33:31
【问题描述】:

我需要一些帮助来在 Matlab 中将元素从短向量映射到更大的向量。我可以使用 for 循环来做到这一点,但我确信有办法避免这种情况。

我有相同大小的输入向量:A = [ 2 3 5 ] 和 B = [ 0.1 0.3 0.23 ]。向量 A 包含“索引”和向量 B 数据。第三个输入向量为 C = [ 2 2 2 3 3 3 3 5 5 ],现在我想生成向量 D = [ 0.1 0.1 0.1 0.3 0.3 0.3 0.3 0.23 0.23 ]。

如何在 Matlab 中生成向量 D,而不使用 for 循环?

提前谢谢你!

【问题讨论】:

    标签: matlab


    【解决方案1】:
    A = [2 3 5];
    B = [0.1 0.3 0.23];
    C = [2 2 2 3 3 3 3 5 5];
    

    使用ismember的第二个输出来创建索引向量:

    [~, ind] = ismember(C, A);
    D = B(ind);
    

    或者,使用interp1:

    D = interp1(A, B, C);
    

    【讨论】:

      【解决方案2】:

      您还可以使用unique 查找C 中每个元素的索引,假设这些值与A 中的值完全对应。如果A 没有排序,那么我们必须先对B 的项目进行排序,以匹配unique 给出的索引:

      A = [2 3 5];
      B = [0.1 0.3 0.23];
      C = [2 2 2 3 3 3 3 5 5];
      
      [~,isort] = sort(A);
      Bsort = B(isort);    % sorted according to A
      [~,~,k] = unique(C); % indices of items in C to pick from A
      D = Bsort(k);        % each matching element from (sorted) B
      

      【讨论】:

        【解决方案3】:

        如果索引向量的元素是正整数,你可以使用索引:

        idx(A,1) = 1:numel(A);
        D = B(idx(C));
        

        如果A 包含大值的正整数,您可以使用稀疏矩阵:

        idx = sparse(A,1,1:numel(A));
        D = B(idx(C));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多