How to shift rows in a matrix by different values (e.g. line 1 n-spots, line 2 m-spots and so on) without using a loop

21 ビュー (過去 30 日間)
I want to shift rows in a matrix randomly. It is im important that every row in shiftet by a random number. I tried to implement it like this but it didn't work. (I could use a loop but that would take too long I guess (I've large amount of data))
cycle=repmat([ones(1,3),zeros(1,7)],5,1); %Matrix with 10 rows that I want to shift
cycle =
1 1 1 1 0 0 0 0 0 0
1 1 1 1 0 0 0 0 0 0
1 1 1 1 0 0 0 0 0 0
1 1 1 1 0 0 0 0 0 0
1 1 1 1 0 0 0 0 0 0
random=round(rand(10,1).*10); % Random values for the shifting for each row
random =
4
6
5
6
9
result=circshift(cycle, [0, random]) % That does not work...
The result would be: result=
cycle =
0 0 0 0 1 1 1 1 0 0 %shifted by 4
0 0 0 0 0 0 1 1 1 1 %shifted by 6
0 0 0 0 0 1 1 1 1 0 %shifted by 5
0 0 0 0 0 0 1 1 1 1 %shifted by 6
1 1 1 0 0 0 0 0 0 1 %shifted by 9
Should i better use another function or what would be the easiest way?
Thanks!

採用された回答

Andrei Bobrov
Andrei Bobrov 2014 年 1 月 7 日
編集済み: Andrei Bobrov 2014 年 1 月 7 日
r = rem(random,10);
c = [cycle,cycle];
out = c(bsxfun(@plus,bsxfun(@plus,10 - r,0:9)*5,(1:5)'));
  2 件のコメント
Tim
Tim 2014 年 1 月 8 日
Thanks a lot, when I tested all the solutions this one was the fastest! ;-)
Miguel Reina
Miguel Reina 2017 年 12 月 25 日
if i have a 577x721 how can i shift the rows from 0 to 576? is like a diagonal shift.

サインインしてコメントする。

その他の回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 1 月 7 日
id=randi(size(cycle,2),1,size(cycle,1))
out=cell2mat(arrayfun(@(x) circshift(cycle(x,:),[1 id(x)]),(1:numel(id))','un',0))

Matt J
Matt J 2014 年 1 月 7 日
編集済み: Matt J 2014 年 1 月 7 日
One way,
round(ifft(fft(cycle,[],2) .* exp(-2i*pi/10*random(:)*(0:9)) ,[],2) )
  3 件のコメント
Matt J
Matt J 2014 年 1 月 7 日
It's just fft's and ifft's. Should work fine.
Tim
Tim 2014 年 1 月 8 日
You're right! it works now!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by