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

时间:2018-12-07 16:54:26

标签: matlab

对于给定的长度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 个答案:

答案 0 :(得分:2)

您可以将索引与模运算符一起使用来解决此问题。唯一的麻烦是MATLAB基于1的索引。我们生成索引1:T,然后使用mod将它们包装起来。由于基于1的索引,我们需要在应用mod之前从索引中减去1,然后再次添加1:

v = 1:12;
T = 15;
output = v(mod(0:T-1,numel(v))+1)

答案 1 :(得分:1)

使用模数解决了该问题:

T = 800

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