1

I want to make left cyclic permutation using MATLAB. Consider matrix p :

p = [2 3 4 5];

Output :

[2 3 4 5; 
 3 4 5 2;
 4 5 2 3;
 5 2 3 4];

I hope the code is available for bigger data. Anyone please help me to make this in code using MATLAB.

Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
yudha25
  • 51
  • 7
  • thanks for you edited @Burkhard , could you help me? – yudha25 Sep 16 '14 at 05:41
  • I'm sorry, my Matlab is a bit rusty. What have you tried so far? – Burkhard Sep 16 '14 at 05:43
  • 1
    I think the `bsxfun` code for left-cyclic permutation in [your previous question](http://stackoverflow.com/q/25857880/2586922) is quite right. You'll end up with a large matrix anyway – Luis Mendo Sep 16 '14 at 07:36
  • Isn't your "bigger" data is `p as 1 x 262144` from [your previous question](http://stackoverflow.com/questions/25857880/out-of-memory-using-bsxfun-matlab)? So aren't you looking to get an output of `262144 x 262144`? That's a huge number really. – Divakar Sep 16 '14 at 09:15

2 Answers2

5

A loop free alternative:

[X, Y] = meshgrid(1:numel(p));
p(mod(X+Y-2,numel(p))+1)
Dan
  • 45,079
  • 17
  • 88
  • 157
  • +1 wonderful, I suggest to add the generic case: `[X, Y] = meshgrid(1:numel(p)); p(mod(X+Y-2,numel(p))+1)` – bla Sep 16 '14 at 08:07
3

This is one approach:

cell2mat(arrayfun(@(n) circshift(p,[0 -n]),0:3,'uni',0).')
ans =
     2     3     4     5
     3     4     5     2
     4     5     2     3
     5     2     3     4

Note that arrayfun is really just a loop disguised as a one-liner. Thus explicitly writing out a loop to do the same thing might be equally fast/slow.

Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70