Repeat and shift array elementwise

조회 수: 6 (최근 30일)
Kai
Kai 2018년 10월 17일
댓글: Kai 2018년 10월 17일
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!

채택된 답변

Matt J
Matt J 2018년 10월 17일
편집: Matt J 2018년 10월 17일
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)
  댓글 수: 1
Kai
Kai 2018년 10월 17일
Amazing, so simple! Thanks a lot! :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by