Repetitive sequence with calculations

Hello all,
I am trying to create the following sequence of numbers:
5 6 7 5 6 7 5 6 7 8 9 10 8 9 10 8 9 10 11 12 13 ...
To be more specific, 5 6 7 will be repeated three times and then +1 to each element and repeat another three times. The amount of iterations would be pre-defined f.e. n times.
This is what I tried but it didn't work:
a=[5 6 7]
x = []
n=9
for i=1:n
s=3+a
for j=1:3
m(i,j)=s(i)
end
b=s+3
x = [x,b];
end
Huge thanks in advance!

 Accepted Answer

a=[5 6 7];
x=zeros(1,9*n);
for j=1:n
x(9*(j-1)+1:9*j)=repmat(a,1,3);
a=a+3;
end

4 Comments

Kyrylo Melnyk
Kyrylo Melnyk on 12 Feb 2020
Edited: Kyrylo Melnyk on 12 Feb 2020
David,
Thanks a lot!
Sorry to bother you but I have another question. If I want to increase the amount of numbers to [5 6 7 8] and then +1 to each element, repeat them 4 times (repeat those steps N times). Basically, what I am trying to say is that I want to change the width (f.e. variable M) of that repetitive component but it doesn't work if I just change '3' to '4'. This is what I tried to do:
n=9;
x=[]
a=[5 6 7 8];
x=zeros(1,9*n);
for j=1:n
x(9*(j-1)+1:9*j)=repmat(a,1,4);
a=a+4;
end
In another words what I really want:
  1. repeat M components for M-times ( 1 2 1 2 next sequence is 3 4 3 4 ..)
  2. add +M to each element after the first step
  3. Repeat this whole process for N times ( f.e. I want to repeat steps 1 and 2 for 15 times)
N=15;
M=[5 6 7 8];
x=zeros(1,length(M)^2*N);
for j=1:N
x(length(M)^2*(j-1)+1:length(M)^2*j)=repmat(M,1,length(M));
M=M+length(M);
end
Thank you so much!
Simpler without a loop, here using repelem:
>> L = numel(M);
>> x = repmat(M,1,L*N) + repelem(L*(0:N-1),L*L)
or using kron:
>> x = repmat(M,1,L*N) + kron(0:N-1,L*ones(1,L*L))

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 12 Feb 2020

Edited:

on 14 Feb 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!