I would appreaciate a lot if you help. I am beginner in programming. I am using Matlab. So, I have an array which is 431x1 type - double; there i have numbers 1 to 6; for ex: 1 4 5 3 2 6 6 3 3 5 4 1 ...; what I want to do is I need to make a new array where I would have each element repeat for 11 times; for ex: a(1:11)=1; a(12:22)=4; a(23:33)=5; or to illustrate differently : a=[1 1 1 1 1 1 1 1 1 1 1 4 4 4 4 4 4 4 4...]; I tried doing it in a loop but had some problems, which way could you suggest, do you know any function I could take advantage of?
-
You can use [repelem](https://www.mathworks.com/help/matlab/ref/repelem.html) – rahnema1 Jan 12 '17 at 17:49
2 Answers
First of all, it would help if you could format your code is separate blocks to make your question easier to read...
Let's say you had an array of length Nx1 as:
x = [1 2 3 4 5 ...]';
You could construct a loop and concatenate as:
for i = 1 : length(x)
for i = 1: length(x)
y(1 + (i - 1) * 11 : 1 + i * 11) = x(i); % Copy to a moving block
end
y(end) = []; % Delete the superfluous one at the end
You could also look at functions like repmat
in the MATLAB help for replicating arrays.

- 594
- 2
- 22
-
thank you! I also tried with repmat inside a loop but again I had trouble with correct indexing to store the replicated values; – Hilola Khaydarova Jan 12 '17 at 23:50
Try this (NRep
is how many times you want it repeated):
x = [1, 2, 3, 4, 5];
NRep = 5;
y = reshape(repmat(x,[NRep,1]),[1,length(x)*NRep])
Since it's a little cumbersome to write that out, I also particularly enjoy to use this "hack":
x = [1, 2, 3, 4, 5];
NRep = 5;
y = kron(x, ones(1,NRep));
Hope that helps!
P.S.: This is designed for row vectors only. Though if you need column vectors it's easy to modify.
edit: Of course, if you're post-R2015a you can just use y=repelem(x,NRep)
. I tend to forget about those because I work on older Matlabs (and sometimes it's not such a bad idea to be a bit backward compatible). Thanks to @rahnema1 for reminding me.

- 1,804
- 2
- 9
- 19
-
thanks a lot!!! this is repelem function which I didnt know about was exactly what I needed :D yayy, your code also worked it gives correct number of repetitions but the problem was that it repeats the whole sequence 11 times rather than replicating each element 11 times; anyway thanks a lot! – Hilola Khaydarova Jan 12 '17 at 23:49