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 Center および File ExchangeSparse Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by