代码之家  ›  专栏  ›  技术社区  ›  WJA

如何为给定长度生成重复元素的向量

  •  2
  • WJA  · 技术社区  · 6 年前

    对于给定长度, T ,我想重复一个有序的序列,直到它到达 T . 顺序是 v = (1:12)' .

    If T = 12, the output vector should be v
    
    If T = 13, the output vector should be v and in addition the first element of v, thus [v; v(1)]
    
    If T = 15, the output vector should be [v; v(1); v(2); v(3)]
    
    If T = 24, the output vector should be [v; v]
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Cris Luengo    6 年前

    您可以使用索引和模运算符来解决这个问题。唯一复杂的是matlab的基于1的索引。我们生成索引 1:T 然后使用 mod 把它们包起来。由于基于1的索引,我们需要在应用之前从索引中减去1 国防部 ,然后再次添加1:

    v = 1:12;
    T = 15;
    output = v(mod(0:T-1,numel(v))+1)
    
        2
  •  1
  •   WJA    6 年前

    用模求解:

    T = 800
    
    v             = (1:12)';
    nbRest        = mod(T,length(v));
    nbFit         = floor(T/length(v));
    currentMonths = [repmat(v, nbFit,1); v(1:nbRest)];