Repeat and shift array elementwise

3 views (last 30 days)
Kai
Kai on 17 Oct 2018
Commented: Kai on 17 Oct 2018
Hey, I have some problem about dealing with arrays. I think it is best explained with some example, so let's say I'm given the vectors
a = [1,3,7,12];
t = [3,1,2,5];
Now what I want to do is to create a new array ashift. In this array the elements a(i) should appear repeatedly t(i) times and then these repetitions should be shifted by 0:t(i)-1 (elementwise). Hence the result should be
ashift = [1,2,3,3,7,8,12,13,14,15,16];
So for example, we have a(4)=12 and t(4)=5, so ashift contains the entries a(4)+0:t(4)-1 = [12,13,14,15,16].
I have looked around and at least found a solution for the "elementwise repitition", but without shifting, in another thread. So this would be:
a = [1,3,7,12];
t = [3,1,2,5];
b = cumsum(t);
c = zeros(1,b(end));
c(b - t + 1) = 1;
arepeat = a(cumsum(c))
arepeat =
1 1 1 3 7 7 12 12 12 12 12
So now if I could create the array
shift = [0,1,2,0,0,1,0,1,2,3,4];
which basically contains these 0:t(i)-4 pieces, then I could say
ashift = arepeat + ashift;
and it would be done. In order to create the array shift, I could use a for loop
shift = [];
for i = 1:length(t)
shift = [shift,0:t(i)-1];
end
This code seems to work, but I don't really like creating the array shift subsequently (I'm sure Matlab will tell me to preallocate). Even if I figured out how to preallocate in here, this for loop still seems inefficient and not very elegant to me.
Any help and idea is appreciated!

Accepted Answer

Matt J
Matt J on 17 Oct 2018
Edited: Matt J on 17 Oct 2018
b=cumsum(t);
adelta=[0,ones(1, b(end)-1 )];
adelta(b(1:end-1)+1)=-t(1:end-1)+1;
ashift=repelem(a,t) + cumsum(adelta)

More Answers (0)

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!