I have an array containing a pattern:
p = [1, 2, 2, 1];
I want to replicate the pattern but need to add the first and last elements. I'd prefer to find a better way than looping, if possible.
Meaning:
[1, 2, 2, 1]
[1, 2, 2, 1]
[1, 2, 2, 2, 2, 2, 1]
I found something that does almost exactly what I need here: https://stackoverflow.com/a/15545970/2434277
But I can't find a way to make the overlap-addition happen. That is, it does this:
[1, 2, 2, 1, 1, 2, 2, 1]
Any ideas?
Thanks!
Quick edit: I'll need to replicate several times, but I don't know the number in advance.
Is it conv that you are looking for ?
> conv([1 0 0 0 1],[1 2 2 1])
1 2 2 1 1 2 2 1
> conv([1 0 0 1],[1 2 2 1])
1 2 2 2 2 2 1
The first argument of conv may also be a sparse matrix:
full(sparse(1,[1 5 18],1))
1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1
conv(full(sparse(1,[1 5 18],1)),[1 2 2 1])
1 2 2 1 1 2 2 1 0 0 0 0 0 0 0 0 0 1 2 2 1
Here's a way:
p = [1, 2, 2, 1];
n = length(p);
p(end + n - 1) = 0; %//pad with 0s
p(n:end) = p(n:end) + p(1:n)
Or you could do it in one line if you want:
[p, zeros(1, length(p)-1] + [zeros(1, length(p)-1, p]
But if you want a general solution for m
repetitions then I suggest you use conv
(as answered by user2987828) like this:
k = []; %// Leave off this line if you are certain that k won't exist yet
n = length(p);
k(1:n-1:(n-1)*m+1)=1;
conv(k,p);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.